C# 从文件名(或目录、文件夹、文件)中删除无效(不允许的、错误的)字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2230826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove invalid (disallowed, bad) characters from FileName (or Directory, Folder, File)
提问by Грозный
I've wrote this little method to achieve the goal in the subj., however, is there more efficient (simpler) way of doing this? I hope this can help somebody who will search for this like I did.
我已经写了这个小方法来实现主题中的目标。但是,有没有更有效(更简单)的方法来做到这一点?我希望这可以帮助像我一样搜索这个的人。
var fileName = new System.Text.StringBuilder();
fileName.Append("*Bad/\ :, Filename,? ");
// get rid of invalid chars
while (fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > -1)
{
fileName = fileName.Remove(fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()), 1);
}
?
?
采纳答案by JaredPar
Try the following
尝试以下
public string MakeValidFileName(string name) {
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach ( var cur in name ) {
if ( !invalid.Contains(cur) ) {
builder.Append(cur);
}
}
return builder.ToString();
}
回答by Benjamin Podszun
If you look for "concise" when you say simple:
如果您在说 simple 时寻找“concise”:
public string StripInvalidChars(string filename) {
return new String(
filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray()
);
}
That said, I'd go with JaredPar's solution. It's probably easier to read (depending on taste, background), my gut feeling is that it is more efficient (although I'm not sure how efficient you have to be stripping that dozen of invalid chars from a limited length filename) and his use of a StringBuilder() seems to fit perfectly to your example.
也就是说,我会选择 JaredPar 的解决方案。它可能更容易阅读(取决于品味、背景),我的直觉是它更有效(尽管我不确定从有限长度的文件名中剥离那十几个无效字符的效率有多高)和他的使用的 StringBuilder() 似乎非常适合您的示例。
回答by Roland Schaer
A different approach that is compatible with .NET 4. See my comments above explaining the need.
一种与 .NET 4 兼容的不同方法。请参阅我上面解释需要的评论。
public static string ScrubFileName(string value)
{
var sb = new StringBuilder(value);
foreach (char item in Path.GetInvalidFileNameChars())
{
sb.Replace(item.ToString(), "");
}
return sb.ToString();
}
回答by Ceres
I know this is a few years old but here is another solution for reference.
我知道这已经有几年了,但这里有另一种解决方案供参考。
public string GetSafeFilename(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}