I want to include a batch file rename functionality in my application. A user can type a destination filename pattern and (after replacing some wildcards in the pattern) I n
If you're only trying to check if a string holding your file name/path has any invalid characters, the fastest method I've found is to use Split()
to break up the file name into an array of parts wherever there's an invalid character. If the result is only an array of 1, there are no invalid characters. :-)
var nameToTest = "Best file name \"ever\".txt";
bool isInvalidName = nameToTest.Split(System.IO.Path.GetInvalidFileNameChars()).Length > 1;
var pathToTest = "C:\\My Folder \\";
bool isInvalidPath = pathToTest.Split(System.IO.Path.GetInvalidPathChars()).Length > 1;
I tried running this and other methods mentioned above on a file/path name 1,000,000 times in LinqPad.
Using Split()
is only ~850ms.
Using Regex("[" + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + "]")
is around 6 seconds.
The more complicated regular expressions fair MUCH worse, as do some of the other options, like using the various methods on the Path
class to get file name and let their internal validation do the job (most likely due to the overhead of exception handling).
Granted it's not very often you need to validation 1 million file names, so a single iteration is fine for most of these methods anyway. But it's still pretty efficient and effective if you're only looking for invalid characters.