This function will take a string and convert it into a folder/file friendly name.

I use it in conjunction with url rewriting, deriving the filename from the title of an article.

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;


This Regex is doesn't account for capital letters or hyphens already in the title ("My Title" becomes "y itle" and "a-b" becomes "a b").

Ravenheart 1


Try that.