Create safe File Name from string using .NET 2.0

|  Posted: May 19, 2007  |  Categories: General Technical

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

Author: Saravana Kumar

Saravana Kumar is the Founder and CTO of BizTalk360 | Serverless360 | Atomic Scope | Document360. Founder of multiple B2B products that solve the pain point of enterprise customers. Entrepreneur, Investor and Technical enthusiast. Passionate about running and scaling a company in a profitable way with calculated risks.

Back to Top