C# string.replace 删除非法字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10898338/
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
C# string.replace to remove illegal characters
提问by Axxelsian
I'm working on a program that reads files and saves pieces of them according to their column's title. Some of those titles have illegal characters for file names, so i've written this piece of code to handle those issues.
我正在开发一个程序,该程序可以根据列标题读取文件并保存其中的一部分。其中一些标题的文件名包含非法字符,因此我编写了这段代码来处理这些问题。
string headerfile = saveDir + "\" + tVS.Nodes[r].Text.Replace("\"", "").Replace
("/","").Replace(":"," -").Replace(">","(Greater Than)") + ".csv";
Is there a nicer way of doing this where i don't have 4 .Replace()? or is there some sort of built in illegal character remover i don't know of?
在我没有 4 的情况下,有没有更好的方法来做到这一点.Replace()?或者是否有某种我不知道的内置非法字符去除器?
Thanks!
谢谢!
EDIT:It does not need to replace the characters with anything specific. A blank space is sufficient.
编辑:它不需要用任何特定的字符替换字符。一个空格就足够了。
采纳答案by Ry-
Regular expressions are generally a good way to do that, but not when you're replacing every character with something different. You might consider replacing them all with the same thing, and just using System.IO.Path.GetInvalidFileNameChars().
正则表达式通常是一个很好的方法,但当你用不同的东西替换每个字符时就不行了。您可能会考虑用相同的东西替换它们,只需使用System.IO.Path.GetInvalidFileNameChars().
string filename = tVS.Nodes[r].Text;
foreach(char c in System.IO.Path.GetInvalidFileNameChars()) {
filename = filename.Replace(c, '_');
}
回答by Jeff Watkins
回答by canon
System.IO.Path.GetInvalidFileNameChars()has all the invalid characters.
System.IO.Path.GetInvalidFileNameChars()包含所有无效字符。
Here's a sample method:
这是一个示例方法:
public static string SanitizeFileName(string fileName, char replacementChar = '_')
{
var blackList = new HashSet<char>(System.IO.Path.GetInvalidFileNameChars());
var output = fileName.ToCharArray();
for (int i = 0, ln = output.Length; i < ln; i++)
{
if (blackList.Contains(output[i]))
{
output[i] = replacementChar;
}
}
return new String(output);
}
回答by Servy
string charsToRemove = @"\/:";TODO complete this list
string filename;
string pattern = string.format("[{0}]", Regex.Escape(charsToRemove));
Regex.Replace(filename, pattern, "");
If you just want to remove illegal chars, rather than replacing them with something else you can use this.
如果您只想删除非法字符,而不是用其他东西替换它们,您可以使用它。

