我需要一个强大的和简单的方法来删除非法的路径和文件字符从一个简单的字符串。我已经使用了下面的代码,但它似乎没有做任何事情,我错过了什么?

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();
        }
    }
}

当前回答

这些都是很好的解决方案,但它们都依赖于Path。getinvalidfilenamecars,它可能不像您想象的那么可靠。请注意MSDN文档中关于Path的以下注释。GetInvalidFileNameChars:

此方法返回的数组不保证包含文件和目录名中无效的完整字符集。完整的无效字符集可能因文件系统而异。例如,在基于windows的桌面平台上,无效路径字符可能包括ASCII/Unicode字符1到31,以及引号(")、小于(<)、大于(>)、管道(|)、退格(\b)、null(\0)和制表符(\t)。

Path的情况也好不到哪里去。GetInvalidPathChars方法。它包含了完全相同的评论。

其他回答

可以试试这样的方法;

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(), ""); 
}

但我不得不同意这些评论,我可能会尝试处理非法路径的来源,而不是试图将非法路径破坏成合法但可能无意的路径。

编辑:或者一个潜在的“更好”的解决方案,使用正则表达式。

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, "");

不过,还是有个问题要问,你为什么要这么做。

最初的问题是“去除非法字符”:

public string RemoveInvalidChars(string filename)
{
    return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
}

相反,你可能想要替换它们:

public string ReplaceInvalidChars(string filename)
{
    return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));    
}

这个答案在Ceres的另一个帖子里,我真的很喜欢它的简洁。

我创建了一个扩展方法,它结合了几个建议:

在哈希集中保存非法字符 过滤ascii 127以下的字符。因为路径。getinvalidfilenamecars不包括ascii码从0到255的所有无效字符。看这里和MSDN 定义替换字符的可能性

来源:

public static class FileNameCorrector
{
    private static HashSet<char> invalid = new HashSet<char>(Path.GetInvalidFileNameChars());

    public static string ToValidFileName(this string name, char replacement = '\0')
    {
        var builder = new StringBuilder();
        foreach (var cur in name)
        {
            if (cur > 31 && cur < 128 && !invalid.Contains(cur))
            {
                builder.Append(cur);
            }
            else if (replacement != '\0')
            {
                builder.Append(replacement);
            }
        }

        return builder.ToString();
    }
}

在windows文件命名中,使用一行程序清除字符串中的任何非法字符:

public static string CleanIllegalName(string p_testName) => new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(p_testName, "");
public static bool IsValidFilename(string testName)
{
    return !new Regex("[" + Regex.Escape(new String(System.IO.Path.GetInvalidFileNameChars())) + "]").IsMatch(testName);
}