Pavel Nasovich's Blog The Moderately Enthusiastic Programmer

Today I Learned: Sanitize File Name in C#

A short update about safe file names in C#.

Sanitize File Name in C

To clean up a file name you could do this

private static string MakeValidFileName(string name)
string invalidChars = new string(Path.GetInvalidFileNameChars())
string escapedInvalidChars = Regex.Escape();
string invalidRegex = string.Format(@"([{0}]*\.+$)|([{0}]+)", escapedInvalidChars);

return Regex.Replace(name, invalidRegex, "_");

Working example you can find on dotnetfiddle

comments powered by Disqus