小编典典

如何从路径和文件名中删除非法字符?

c#

我需要一种健壮且简单的方法来从简单的字符串中删除非法的路径和文件字符。我使用了下面的代码,但是它似乎什么也没做,我想念的是什么?

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";

            illegal = illegal.Trim(Path.GetInvalidFileNameChars());
            illegal = illegal.Trim(Path.GetInvalidPathChars());

            Console.WriteLine(illegal);
            Console.ReadLine();
        }
    }
}

阅读 505

收藏
2020-05-19

共1个答案

小编典典

尝试这样的事情;

string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());

foreach (char c in invalid)
{
    illegal = illegal.Replace(c.ToString(), ""); 
}

但是我必须同意这些意见,我可能会尝试处理非法路径的来源,而不是试图将非法路径变为合法但可能是意想不到的路径。

编辑:或者使用Regex的潜在“更好”的解决方案。

string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");

仍然有个问题要问,为什么首先要这样做。

2020-05-19