You can do it this way (using the System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName) { Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]"); if (containsABadCharacter.IsMatch(testName) { return false; };
[edit]
If you want the regular expression to check the folder path, you can use it:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I remembered one difficult thing that allows you to check the correctness of the path:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)
source share