Creates a valid file name. - CSharp System.IO

CSharp examples for System.IO:File Name

Description

Creates a valid file name.

Demo Code

//   The MIT License (MIT)
using System.Text.RegularExpressions;
using System.Text;
using System.Collections;
using System;//from w  w  w  .  j av  a 2 s  . c  o  m

public class Main{
        /// <summary>
        /// Creates a valid file name.
        /// </summary>
        /// <param name="title">
        /// The title.
        /// </param>
        /// <param name="extension">
        /// The extension.
        /// </param>
        /// <returns>
        /// A file name.
        /// </returns>
        public static string CreateValidFileName(string title, string extension)
        {
            string validFileName = title.Trim();
            var invalidFileNameChars = "/?<>\\:*|\0\t\r\n".ToCharArray();
            foreach (char invalChar in invalidFileNameChars)
            {
                validFileName = validFileName.Replace(invalChar.ToString(), string.Empty);
            }

            foreach (char invalChar in invalidFileNameChars)
            {
                validFileName = validFileName.Replace(invalChar.ToString(), string.Empty);
            }

            if (validFileName.Length > 160)
            {
                // safe value threshold is 260
                validFileName = validFileName.Remove(156) + "...";
            }

            return validFileName + extension;
        }
}

Related Tutorials