Click here to Skip to main content
13,191,642 members (64,486 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 20 Feb 2013

Remove Illegal Chars from a File and/or Folder Name

, 20 Feb 2013
Rate this:
Please Sign up or sign in to vote.
A simple regex that replaces ALL the illegal filename or path chars


When you wish to check a new name for a folder or file, you perform a validate function. This function may vary according to the implementer.

Most of us will just write down a simple function to remove the illegal chars such as < > : " / \ | ? * (on Windows) like replacing those chars with "" e.g.:

Str = Str.Replace("<", "");  

However, you are missing a lot of uncommon chars that are not allowed, (many of which you don't have on your keyboard [even in China!]) and (though somewhat unlikely) those may even vary with time. The idea is to use the .NET-provided illegal chars of the Path class, and to replace them with Regex.


Here goes:

public static string FixedStr(string Str)
    // This regex will include illegal chars you never dreamed of
    string illegalCharsPattern = new string(Path.GetInvalidFileNameChars()) 
         + new string(Path.GetInvalidPathChars());
    Regex r = new Regex(string.Format("[{0}]", Regex.Escape(illegalCharsPattern))); 
    return r.Replace(Str, ""); 

NOTE: This is not for old systems with SFN 8.3 file name requirement (like FAT), for file names and some special UNIX systems (though UNIX usually allows most chars).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Joezer BH
Chief Technology Officer
United States United States
Senior dish washing consultant for over 25 years!

You may also be interested in...

Comments and Discussions

GeneralMy vote of 4 Pin
Cindy Meister22-Feb-13 7:17
memberCindy Meister22-Feb-13 7:17 
It would be nice to have more information in the Note as it is not clear what is meant and why there might be problems?
GeneralRe: My vote of 4 Pin
Edo Tzumer24-Feb-13 21:22
memberEdo Tzumer24-Feb-13 21:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171017.2 | Last Updated 21 Feb 2013
Article Copyright 2013 by Joezer BH
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid