The Solution
It’s very useful for generating safe file or folder names from text that a user inputs.
public static string CleanStringForFileSystem(string dirtyFileName)
{
// first trim the raw string
string safe = dirtyFileName.Trim();
// replace spaces with hyphens
safe = safe.Replace(" ", "-").ToLower();
// replace any 'double spaces' with singles
if (safe.IndexOf("--") > -1)
while (safe.IndexOf("--") > -1)
safe = safe.Replace("--", "-");
// trim out illegal characters
safe = Regex.Replace(safe, "[^a-z0-9\\-]", "");
// trim the length
if (safe.Length > 50)
safe = safe.Substring(0, 49);
// clean the beginning and end of the filename
char[] replace = { '-', '.' };
safe = safe.TrimStart(replace);
safe = safe.TrimEnd(replace);
return safe;
}