How to remove illegal characters from path and filenames?

前端 未结 29 3342
离开以前
离开以前 2020-11-22 17:18

I need a robust and simple way to remove illegal path and file characters from a simple string. I\'ve used the below code but it doesn\'t seem to do anything, what am I miss

29条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 17:46

    Here's a code snippet that should help for .NET 3 and higher.

    using System.IO;
    using System.Text.RegularExpressions;
    
    public static class PathValidation
    {
        private static string pathValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]+$";
        private static Regex pathValidator = new Regex(pathValidatorExpression, RegexOptions.Compiled);
    
        private static string fileNameValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]+$";
        private static Regex fileNameValidator = new Regex(fileNameValidatorExpression, RegexOptions.Compiled);
    
        private static string pathCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]";
        private static Regex pathCleaner = new Regex(pathCleanerExpression, RegexOptions.Compiled);
    
        private static string fileNameCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]";
        private static Regex fileNameCleaner = new Regex(fileNameCleanerExpression, RegexOptions.Compiled);
    
        public static bool ValidatePath(string path)
        {
            return pathValidator.IsMatch(path);
        }
    
        public static bool ValidateFileName(string fileName)
        {
            return fileNameValidator.IsMatch(fileName);
        }
    
        public static string CleanPath(string path)
        {
            return pathCleaner.Replace(path, "");
        }
    
        public static string CleanFileName(string fileName)
        {
            return fileNameCleaner.Replace(fileName, "");
        }
    }
    

提交回复
热议问题