Validating Sharepoint filenames on upload

Some characters are legal for FAT or NTFS files but illegal for files in Sharepoint documentlibraries. Using the regular upload UI for Sharepoint you'll encounter a rather unpleasant validation error when uploading a file with funky characters. Using the object model will give you a good ole' exception.

I've seen a lot of approaches to solving this problem, and implemented a couple myself. Last night I noticed a method on the SPEncode static class that enabled a clean approach to the problem (updated for double punctuation mark problem):

private string CleanForUrlAndFileNameUse(string dirtyFileName)


    char[] dirtyChars = dirtyFileName.ToCharArray();

    foreach (char c in dirtyChars)


        if (!SPEncode.IsLegalCharInUrl(c))


            dirtyFileName = dirtyFileName.Replace(c.ToString(), "");




    // Spaces are not appreciated

    dirtyFileName = dirtyFileName.Replace(" ", "");


    // double punctuation marks causes validation error

    while(dirtyFileName.IndexOf("..") != -1)

        dirtyFileName = dirtyFileName.Replace("..", ".");


    return dirtyFileName; // now clean:-)



Comments have been disabled for this content.