C #: Remove invalid characters from file name string

Why does this not do anything, the output is identical to input? I am puzzled !!!

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

string valid = Regex.Replace(name, "[" + invalidString + "]", "");
+3
source share
3 answers

EDIT:

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

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 the output of "true.jpg". I would definitely suggest a lot more tests before using this in production! :)

+6
source

What do you mean by this will not 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 incorrect, you had some unescaped characters, and you were missing a semicolon.

.

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

. , , , , , , .

: ? , , , :

System.IO.Path.GetInvalidFileNameChars();

: , 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'
     };

, ASCII/Unicode 1 31, ("), (<), ( > ), pipe (|), backspace (\ b), null (\ 0) tab (\ t).

.

+4

,

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

Source: https://habr.com/ru/post/1717306/


All Articles