In my application the user can enter a filename. Before processing I'd like to check if the input String is a valid filename on Windows Vista.
Whats the easiest way to do that?
By valid I'm reffering to legal and non-existing
We can use the String. contains() method to check if the given String holds any of the forbidden characters.
File names can contain any of the following characters: A-Z, a-z, 0-9, underscore, hyphen, space, period, parenthesis, curly braces, square brackets, tilde, exclamation point, comma, semicolon, apostrophe, at sign, number sign, dollar sign, percent sign, plus sign, and equal sign.
Check whether filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0
and !File.Exists(Path.Combine(someFolder, filename))
Check against GetInvalidFileNameChars()
:
var isValid = !string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && !File.Exists(Path.Combine(sourceFolder, fileName));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With