Revision #2

You are currently reviewing an older revision of this page.
Go to current version
Convert a SharePoint name to a Friendly name that you can save, returning max of 180 characters
private static readonly Regex InvalidCharsRegex =
        new Regex(@"[\*\?\|\\\t/:""'<>#{}%~&]", RegexOptions.Compiled);
 
        private static readonly Regex InvalidRulesRegex =
        new Regex(@"\.{2,}", RegexOptions.Compiled);
 
        private static readonly Regex StartEndRegex =
        new Regex(@"^[\. ]|[\. ]$", RegexOptions.Compiled);
 
        private static readonly Regex ExtraSpacesRegex =
        new Regex(" {2,}", RegexOptions.Compiled);
 
        /// <summary>
        /// Returns a folder or file name that
        /// conforms to SharePoint's naming restrictions
        /// </summary>
        /// <param name="original">
        /// The original file or folder name. 
        /// For files, this should be the file name without the extension.
        /// </param>
        public static string GetSharePointFriendlyName(string original)
        {
            // remove invalid characters and some initial replacements
            var friendlyName = ExtraSpacesRegex.Replace(
            InvalidRulesRegex.Replace(
            InvalidCharsRegex.Replace(
            original, String.Empty).Trim()
            , ".")
            , " ");
 
            // Check beginning and end for periods and spaces
            while (StartEndRegex.IsMatch(friendlyName))
                friendlyName = StartEndRegex.Replace(
                friendlyName, String.Empty);
 
            return friendlyName.Length > 180 ? friendlyName.Substring(0, 180) : friendlyName;
        }
Revert to this revision