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, an enterprise software that acts as an all-in-one solution for better administration, operation, support and monitoring of Microsoft BizTalk Server environments.

One Platform Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

ServiceBus360

Azure Composite Application

Learn more

Start manage and monitor your Azure Services in minutes

One Platform - Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

One Platform - Operations, Monitoring and Analytics Software
ServiceBus360

Azure Composite Application

Learn more

Start manage and monitor your Azure Services in minutes

Back to Top