How to remove illegal characters from path and filenames?

前端 未结 29 3364
离开以前
离开以前 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:42

    public static class StringExtensions
          {
            public static string RemoveUnnecessary(this string source)
            {
                string result = string.Empty;
                string regex = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
                Regex reg = new Regex(string.Format("[{0}]", Regex.Escape(regex)));
                result = reg.Replace(source, "");
                return result;
            }
        }
    

    You can use method clearly.

提交回复
热议问题