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:-)

}

Filed under:

Comments

# Angus Logan said:

Hey Mads - Nice one!

Wanna wrap it up in a console app which cleans entire directories?

Thursday, November 17, 2005 5:40 AM
# Mirrored Blogs said:

I've developed various solutions to this in various SharePoint projects, but I found a nice neat

Friday, August 17, 2007 4:05 PM
# deepmala said:

Hi Mads,

i have a requirement of searching the file in a document library on the basis of File Name and Type, here Type will define its extension.

any help would be appreciated.

Tuesday, September 11, 2007 2:56 AM
# Rabbit66 said:

Where would I add this code? Not a programmer?

Wednesday, October 17, 2007 4:14 PM
# Frank said:

SharePoint vs. File Shares

Of corse file shares!

Tuesday, September 09, 2008 6:08 PM
# devendra said:

Where i have to place this code

Wednesday, January 07, 2009 2:44 AM
# elexx-fm said:

<a href= http://adultchatsfinder.com >chat online</a>

Sunday, March 01, 2009 1:59 AM
# Olgunka-cd said:

<a href= adultspeeddatingfinder.com >singles</a>

Sunday, March 01, 2009 2:01 AM
# Manitra said:

Hello,

Thanks for this tip. I would suggest a small enhancement to drastically increase the speed and reduce the memory consumption :

   // has a N complexity instead of N^2 for your implementation (N being the number of char)

   //moreover, memory consumption is reduced

   var result = new StringBuilder(dirtyFileName.Length);

   foreach (var c in dirtyFileName.ToCharArray())

       if (!SPEncode.IsLegalCharInUrl(c))

           result.Append(c);

   return result.ToString();

I hope this would be usefull.

Manitra.

Thursday, June 03, 2010 8:12 AM