Tuesday, November 18, 2008

Get a Valid SharePoint File Or Folder Name

If you're programatically uploading files to a SharePoint document library or creating folders, the file or folder name must not contain certain invalid characters. If it does, you'll get an error, for example:

The file or folder name ".." contains invalid characters. Please use a different name. Invalid characters include the following: ~ " # % & * : < > ? / \ { | }. The name cannot begin or end with dot and cannot contains consecutive dots.

File or folder names must also be less than or equal to 128 characters in length. In addition, the total unescaped URL length (less the length of the URI authority e.g. http://localhost:2008/) must not exceed 260 characters.

The following code uses a regular expression to validate a file or folder name before it is uploaded or created (without checking the total URL length):

using System;
using System.Web;
using System.Text.RegularExpressions;
 
namespace DevHoleDemo
{
    class Program
    {
        static Regex illegalPathChars = new Regex(@"^\.|[\x00-\x1F,\x7B-\x9F,"",#,%,&,*,/,:,<,>,?,\\]+|(\.\.)+|\.$", RegexOptions.Compiled);
 
        static void Main(string[] args)
        {
            string fileName = "/new%20file.txt";
            string validFileName = fileName;
 
            if (GetValidFileOrFolderName(ref validFileName))
                Console.WriteLine("A valid file or folder name for '{0}' is '{1}'.", fileName, validFileName);
            else
                Console.WriteLine("Could not get a valid file or folder name.");
        }
 
        public static bool GetValidFileOrFolderName(ref string path)
        {
            return GetValidFileOrFolderName(ref path, '_');
        }
 
        public static bool GetValidFileOrFolderName(ref string path, char replacementChar)
        {
            if (path == null)
                return false;
            path = illegalPathChars.Replace(HttpUtility.UrlDecode(path.Trim()), replacementChar.ToString());
            if (path.Length > 128)
            {
                path = path.Substring(0, 128);
                return GetValidFileOrFolderName(ref path, replacementChar);
            }
            return path.Length > 0;
        }
    }
}

2 comments:

najeh said...

Hi all;
Please, is there any function to retrive all special characters? I used the system function : Path.GetInvalidFileNameChars(); but I didn't get all sharepoint forbidden characters.

Thanks.

Anonymous said...

It works perfect.

Thank you.