Select Page

Validate that file name before uploading a file to the SharePoint library!

SharePoint has hard limits on the characters which can be used in the file names. But somehow, I have seen a lot of SharePoint solutions which do not consider that limits, and the error messages about not allowed characters in the file names are popping all the time.

Microsoft has published the whole list of not allowed characters here:

Obviously, the only right way before storing the file in the SharePoint library in custom solution is to validate its name before the upload operation. I’ve seen many different ways to validate the  name, some better and some worse, but it’s somehow not that well known that there is a SPEncode class in Microsoft.SharePoint.Utilities namespace which can really help us to implement the file name validation which covers all of the cases which SharePoint does not like.

Take a look at the SPEncode class. Hence, take a look at the whole Microsoft.SharePoint.Utilities namepace, there are some cool things there 🙂

For now a nice validation method based on it:

/// <summary>
/// Validates a file name before upload to the sharepoint library.
/// </summary>
/// <param name="fileName">Original file name</param>
/// <returns>Clean file name</returns>
private string cleanFileName(string fileName)
    string ext = Path.GetExtension(fileName);
    string name = Path.GetFileNameWithoutExtension(fileName);

     //first remove double fullstops (..)
     while (name.Contains(".."))
         name = name.Replace("..", "__");

     //name only is not allowed to end with fullstop (.)
     if (name.EndsWith("."))
         name = name.Substring(0, name.Length - 1) + "_";

     //now use "SPEncode.IsLegalCharInUrl()" to remove characters which sharepoint does not like
     char[] filenameChars = name.ToCharArray();
     foreach (char c in filenameChars)
         if (!SPEncode.IsLegalCharInUrl(c)) name = name.Replace(c.ToString(), "");

     //return clean filename
		return string.Format("{0}{1}", name, ext);return string.Format("{0}{1}", name, ext);