如何删除路径和文件名非法字符? [英] How to remove illegal characters from path and filenames?

查看:1144
本文介绍了如何删除路径和文件名非法字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 使用系统;
使用System.IO;命名空间的ConsoleApplication1
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            串非法=\\并购下;> \\\\\\一个/ RY /小时**广告:GT;>一种\\\\ /?* \\&所述;> |李* TT |乐||羊肉。?;            非法= illegal.Trim(Path.GetInvalidFileNameChars());
            非法= illegal.Trim(Path.GetInvalidPathChars());            Console.WriteLine(非法的);
            到Console.ReadLine();
        }
    }
}


解决方案

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

 字符串非法=\\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.

这篇关于如何删除路径和文件名非法字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆