如何从路径和文件名中删除非法字符? [英] How to remove illegal characters from path and filenames?
本文介绍了如何从路径和文件名中删除非法字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种强大而简单的方法来从一个简单的字符串中删除非法的路径和文件字符.我使用了下面的代码,但它似乎没有做任何事情,我错过了什么?
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();
}
}
}
推荐答案
试试这样的方法;
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.
或者一个潜在的更好"的解决方案,使用正则表达式.
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屋!
查看全文