Create safe File Name from string using .NET 2.0

Published on : May 19, 2007

Category : General

Saravana

Author

Recently for one of my weekend project I wanted to create a safe file name from a string. In the past people used to do lot of regular expressions and conditional testing to meet this requirement. Still the filename won’t be safe across multiple environments (Windows 2000/XP/2003 etc). But with .NET 2.0 using couple of inbuild functions (Path.GetInvalidFileNameChars and Path.GetInvalidPathChars) you can create safe filenames. Hope this piece of code will be useful to someone. private string CreateValidFileName(string title, string extension) { string validFileName = title.Trim(); foreach (char invalChar in Path.GetInvalidFileNameChars()) { validFileName = validFileName.Replace(invalChar.ToString(), “”); } foreach (char invalChar in Path.GetInvalidPathChars()) { validFileName = validFileName.Replace(invalChar.ToString(), “”); } if (validFileName.Length > 160) //safe value threshold is 260 validFileName = validFileName.Remove(156) + “…” return validFileName + “.” + extension; } Nandri! Saravana