How to remove illegal characters from path and filenames?

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

    I think the question already not full answered... The answers only describe clean filename OR path... not both. Here is my solution:

    private static string CleanPath(string path)
    {
        string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
        Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
        List split = path.Split('\\').ToList();
        string returnValue = split.Aggregate(string.Empty, (current, s) => current + (r.Replace(s, "") + @"\"));
        returnValue = returnValue.TrimEnd('\\');
        return returnValue;
    }
    

提交回复
热议问题