Gotcha: System.IO.GetInvalidPathChars result not guaranteed
at System.IO.Path.GetInvalidPathChars one reads:
The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names
note: can also call this method from non-trusted Silverlight app – not as Intellisense tooltip wrongly says in Visual Studio 2013 with Silverlight 5.1
I just found out about this the hard way (since DotNetZip library was failing at SelectFiles to open .zip files that it had before successfully saved with item filenames containing colons). So I had to update my ReplaceInvalidFileNameChars string extension method to also replace/remove invalid characters such as the colon, wildcard characters (* and ?) and double quote.
public static string ReplaceInvalidFileNameChars(
this string s,
string replacement = "") { return Regex.Replace(s, "[" + Regex.Escape( Path.VolumeSeparatorChar + Path.DirectorySeparatorChar + Path.AltDirectorySeparatorChar + ":" + //added to cover Windows & Mac in case code is run on UNIX "\\" + //added for future platforms "/" + //same as previous one "<" + ">" + "|" + "\b" + "" + "\t" + //based on characters not allowed on Windows new string(Path.GetInvalidPathChars()) + //seems to miss *, ? and " "*" + "?" + "\"" ) + "]", replacement, //can even use a replacement string of any length RegexOptions.IgnoreCase); //not using System.IO.Path.InvalidPathChars (deprecated insecure API) }
Useful to know:
System.IO.Path.VolumeSeparatorChar
slash ("/") on UNIX, and a backslash ("\") on the Windows and Macintosh operating systems
System.IO.Path.DirectorySeparatorChar
slash ("/") on UNIX, and a backslash ("\") on the Windows and Macintosh operating systems
System.IO.Path.AltDirectorySeparatorChar
backslash (‘\’) on UNIX, and a slash (‘/’) on Windows and Macintosh operating systems
More info on illegal characters at various operating systems can be found at: