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;
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.
Still, the question begs to be asked, why you're doing this in the first place.
You can use method clearly.
I think the question already not full answered... The answers only describe clean filename OR path... not both. Here is my solution:
I created an extension method that combines several suggestions:
Source:
Throw an exception.
I absolutely prefer the idea of Jeff Yates. It will work perfectly, if you slightly modify it:
The improvement is just to escape the automaticially generated regex.