Loading ...

C#: Remove illegal characters from path and filenames | CodeAsp.Net

C#: Remove illegal characters from path and filenames

 /5
0 (0votes)

If you want to remove invalid chars "* . " / \ [ ] : ; | = ," from file name below is the code which can help you

Sample code:

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

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string illegal = "\"A\"\\b/cd/ g**hj:>> i\\/:*?\"| jk*lm|mn|| op\"qr.?";
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            illegal = r.Replace(illegal, "");
            Console.WriteLine(illegal);
            Console.ReadLine();
        }
    }
}

Output:

Comments (no comments yet)

Top Posts