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

标签 c# string path directory

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

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

最佳答案

试试这样的方法;

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

不过,还是要问一个问题,您一开始为什么要这样做。

关于c# - 如何从路径和文件名中删除非法字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/146134/

相关文章:

c# - 为什么我的 c# paint 方法内存不足?

c# - 我可以让 WebApi 与 IoC Aspects/Interceptor 一起工作吗

C++ - 向字符串添加空格

python - 在 Python 中解码双重编码的 utf8

path - 如何将交叉编译器添加到PATH

c# - 在 Windows 10 edge 上运行自动化测试是否需要进行任何特殊设置

c# - 在 SwaggerUI 中隐藏/显示 Controller (可配置)

Python 在 Print 语句中打印和乘以字符串

java - 如何通过 Groovy 获取文件 build.gradle 的完整路径?

XSLT 相对或绝对路径,意外行为