Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Removing characters which are not allowed in Windows filenames

0.00/5 (No votes)
13 Apr 2014 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here