Possible Duplicate:
How check if given string is legal (allowed) file name under Windows?
I am new to stackoverflow. I know its a silly question, but I am stuck in it. I want to validate a filename so that it should only accept legal path. I have tried the below code:
if (txtFileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}
It worked, however, I was a bit confused whether it will fully work or not so I wanted to know other answers too. I think we can also validate a filename using Regular Expression too. Any help will be great.
This will work as expected.
There's no need to invent a regular expression to do this as if the set of invalid characters ever changes you're code will be out of date, whereas this call will still work as expected.
That's the correct way to go. In future, if your program will be ported to a different operating system, it will continue to work. Hand made solutions will be less effective.
Try this:
bool bOk = false;
try
{
new System.IO.FileInfo(fileName);
bOk = true;
}
catch (ArgumentException)
{
}
catch (System.IO.PathTooLongException)
{
}
catch (NotSupportedException)
{
}
if (!bOk)
{
// ...
}
else
{
// ...
}
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