I wrote this function about a year ago, it's very useful for generating safe file or folder names from text that a user inputs.
One method I use this for is storing the filename in the database and then url-rewriting with global.asax. You can get an example of url rewriting here.
public static string FilenameFromTitle(string name)
{
// first trim the raw string
string safe = name.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;
}