Introduction
It's easy to remove a characater from a string in c#:
myString = myString.Replace(":", "");
Will do it. But...it's kinda clumsy to repeat that for all the illegal characters in a filename - not to mention wasteful, since it creates a new string for each character you try to remove. Why can't you just go:
MyString = myString.RemoveAll(@"\/:*?""<>|");
Well...because the method doesn't exist...:laugh:
Using the code
A little regex makes it all so simple:
Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]");
string myString = illegalInFileName.Replace(myString, "");
All done!
Or better (though a little less readable):
private Regex illegalInFileName = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()))), RegexOptions.Compiled);
...
string myString = @"A\\B/C:D?E*F""G<H>I|";
myString = illegalInFileName.Replace(myString, "");
This method suggested by Michael_Davies[^] and for which I am most grateful!
History
2014 Apr 14 Original version.
2014 Apr 14 Addition of a technically better version.