The Kirkland Coder: 2015

Friday, April 10, 2015

File Name Validation

In a continuing effort to keep track of my coding notes, here is another function I wrote that I use a lot. It uses "Path" to get a list of invalid characters to check against.

 using System;
using System.IO;
using System.Text.RegularExpressions;

namespace DemoSolution
{
    class Program
    {
        static void Main(string[] args)
        {
            string badFileName = @"This!has*INVALID:characters.txt";
            string goodFileName = @"This-has_INVALID.characters.txt";

            Console.WriteLine("badFileName = {0}", badFileName.IsValidFileName());
            // OUTPUT: badFileName = False

            Console.WriteLine("goodFileName = {0}", goodFileName.IsValidFileName());
            // OUTPUT: goodFileName = True
        }
    }

    public static class MyExtensions
    {
        /// 
        /// Checks the string to see if any invalid characters exist for a file name.
        /// 
        /// 
        /// 
        ///     Returns "True" if the file name has no invalid
        ///     characters, else it returns "False".
        /// 
        /// 
        /// string fileName = "Valid_File-Name.txt";
        /// 
        public static bool IsValidFileName(this string FileName)
        {
            // Create the RegEx pattern to match
            Regex BadPathCharacters = new Regex(
                "[" + Regex.Escape(String.Join("", Path.GetInvalidFileNameChars()))
                + "]");

            // See if any of the characters are a match. 
            if (BadPathCharacters.IsMatch(FileName))
            {
                return false;
            }
            return true;
        }
    }
}