且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-18 18:36:46

尝试这样的事情,而不是;

 字符串非法=\\M \\\\\\ A / RY / H **广告:>>将\\\\ /:*?\\|李* TT |乐||羊肉。?;
字符串无效=新的字符串(Path.GetInvalidFileNameChars())+新的字符串(Path.GetInvalidPathChars());的foreach(无效字符C)
{
    非法= illegal.Replace(c.ToString(),);
}

但我有意见同意,我可能会尝试解决非法路径的来源,而不是试图裂伤非法路径成合法的,但可能是意外的。

编辑:或潜在的'好'的解决方案,使用正则表达式的

 字符串非法=\\M \\\\\\ A / RY / H **广告:>>将\\\\ /:*?\\|李* TT |乐||羊肉。?;
字符串regexSearch =新的字符串(Path.GetInvalidFileNameChars())+新的字符串(Path.GetInvalidPathChars());
正则表达式R =新的正则表达式(的String.Format([{0}],Regex.Escape(regexSearch)));
非法= r.Replace(非法的,);

不过,回避问题要问,为什么你在第一时间这样做。

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 missing?

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

Try something like this instead;

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

But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one.

Edit: Or a potentially 'better' solution, using Regex's.

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

Still, the question begs to be asked, why you're doing this in the first place.