Removing characters which are not allowed in Windows filenames






4.93/5 (19 votes)
Sometimes, I need to create files or folders directly, and use existing data to provide the file name - and then my app throws an exception because there are "illegal characters in the file name" - so this is a simple way to remove them.
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.