Generate safe file/folder names from user input

ben_ 0 Tallied Votes 130 Views Share

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;
}
mist83 0 Newbie Poster

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 Light Poster
MyString.Trim(Path.GetInvalidFileNameChars()).Trim(Path.GetInvalidPathChars());

Try that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.