Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains invalid filename characters in c#?

Tags:

string

c#

search

I have a string and I want to check if it contains any invalid filename characters. I know I could use

 Path.GetInvalidFileNameChars 

to get a array of invalid filename characters and loop through to see if the string contains any invalid char. But is there a easier and shorter expression? It is c#. So can anyone help?

like image 400
An Overflowed Stack Avatar asked Nov 23 '25 19:11

An Overflowed Stack


1 Answers

bool containsInValidFilenameCharacters(string str) {
    return str.Any(Path.GetInvalidFileNameChars().Contains)
}

Note that this is the same as doing

var invalidChars = Path.GetInvalidFileNameChars();
return str.Any(c => invalidChars.Contains(c));

But since the type signature of Contains matches up exactly with the parameter delegate type of Any we can just pass it directly and it will do an implicit conversion.

like image 158
George Mauer Avatar answered Nov 26 '25 07:11

George Mauer