Wednesday, April 20, 2011

C# FileName Remove Special Characters not Allowed in FileName

While generating a filename programatically/dynamically by accepting the filename as user input, it is mandatory to make the raw filename valid by removing the special characters if given.

The following are the special characters which are not allowed in filename.
\/:*?"<>|#%&.{}~
Note: Period(.) is allowed but as filename can't be start or end with it and consecutive periods(.. or ...) are not allowed, considering it as invalid char for filename.
using System;
using System.Linq;
private static string GetValidFileName(string rawFileName)
{
  string fileName = rawFileName;
  //special chars not allowed in filename
  string specialChars = @"\/:*?""<>|#%&.{}~";
  //Replace special chars in raw filename with empty spaces to make it valid
  Array.ForEach(specialChars.ToCharArray(), specialChar => fileName = fileName.Replace(specialChar, ' '));
  fileName = fileName.Replace(" ", string.Empty);//Recommended to remove the empty spaces in filename
  return fileName;
}

To know more about filename constraints, look at the detailed post here.