Question

Why won't this do anything, output is identical to input? I'm baffled!!!

string name = ";;;'']][[ zion \\\[[[]]]"  
char[] invalidChars = System.IO.Path.GetInvalidPathChars();
string invalidString = Regex.Escape(new string(invalidChars));

string valid = Regex.Replace(name, "[" + invalidString + "]", "");
Was it helpful?

Solution

EDIT:

I think it may just be a case of imperfect test data (along with the function change that others have suggested). Try this:

string name = "tru\\e.jpg";
char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
string invalidString = Regex.Escape(new string(invalidChars));
string valid = Regex.Replace(name, "[" + invalidString + "]", "");
Console.WriteLine(valid);

I get "true.jpg" output. I would definitely suggest much more testing before using this in production! :)

OTHER TIPS

Get invalid file characters using,

char[] invalidChars=System.IO.Path.GetInvalidFileNameChars();

What do you mean by it won't do anything? I ran the following in a console application:

string name = ";;;'']][[ zion \\\\[[[]]]";
char[] invalidChars = System.IO.Path.GetInvalidPathChars();
string invalidString = Regex.Escape(new string(invalidChars));

string valid = Regex.Replace(name, "[" + invalidString + "]", "");
Console.WriteLine(valid);

By the way your syntax was wrong, you had some unescaped characters and you were missing a semi-colon.

And I got the following result.

;;;'']][[ zion \\[[[]]]

Which is the correct result. Maybe you should ask a new question about what you are trying to do because your current approach seems to indicate that you don't have a strong understanding of Regex.

Update: Are you trying to check files names? If so you probably want to use:

System.IO.Path.GetInvalidFileNameChars();

Update: Here is a list of invalid characters that comes from that method GetInvalidPathChars()

RealInvalidPathChars = new char[] { 
        '"', '<', '>', '|', '\0', '\x0001', '\x0002', '\x0003', '\x0004', '\x0005', '\x0006', '\a', '\b', '\t', '\n', '\v', 
        '\f', '\r', '\x000e', '\x000f', '\x0010', '\x0011', '\x0012', '\x0013', '\x0014', '\x0015', '\x0016', '\x0017', '\x0018', '\x0019', '\x001a', '\x001b', 
        '\x001c', '\x001d', '\x001e', '\x001f'
     };

So basically the following are invalid path characters might include ASCII/Unicode characters 1 through 31, as well as quote ("), less than (<), greater than (>), pipe (|), backspace (\b), null (\0) and tab (\t).

None of which seem to occur in your original string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top