Path.GetInvalidFileNameChars and Path.GetInvalidPathChars
Path.GetInvalidFileNameChars method gets an array containing the characters that are not allowed in file names.
Path.GetInvalidPathChars method gets an array containing the characters that are not allowed in path names.
The following C# code snippest shows you how to use the above two methods to remove illegal path and file characters from a simple string:
string filepath = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
foreach (char c in Path.GetInvalidFileNameChars())
{
filepath = filepath.Replace(c.ToString(), "");
}
foreach (char c in Path.GetInvalidPathChars())
{
filepath = filepath.Replace(c.ToString(), "");
}
Or using Regex
string filepath = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = string.Format("{0}{1}",
new string(Path.GetInvalidFileNameChars()),
new string(Path.GetInvalidPathChars()));
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
filepath = r.Replace(filepath, "");