Often I need to clean a file name using Path.GetInvalidFileNameChars(), however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass.
public string LoopMethod()
{
StringBuilder sb = new StringBuilder(fileName);
foreach(var invalidChar in Path.GetInvalidFileNameChars())
{
sb.Replace(invalidChar, '_');
}
return sb.ToString();
}
Regex invalidCharsRegex;
public void RegexMethodInit()
{
var invalidChars = Path.GetInvalidPathChars().Select(c => Regex.Escape(c.ToString())).ToString();
invalidCharsRegex = new Regex(string.Join("|", invalidChars));
}
public string RegexMethod(string fileName)
{
return invalidCharsRegex.Replace(fileName, "_");
}
Is one of those ways the "correct" way to to this or is there a better function I am missing?
char[]of characters that are illegal in a file name. What I wanted to know is what is the proper way to clean a filename from the returnedchar[], is it to just loop like in my example, or is there a function that can take in a char[] and replace on a string in one operation? – Scott Chamberlain Feb 22 at 0:11