7

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.

Community
  • 1
  • 1
Running Rabbit
  • 2,634
  • 15
  • 48
  • 69

4 Answers4

3

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
1

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.

Steve
  • 213,761
  • 22
  • 232
  • 286
1

Try this:

bool bOk = false; 
try 
{ 
    new System.IO.FileInfo(fileName); 
    bOk = true; 
} 
catch (ArgumentException) 
{ 
} 
catch (System.IO.PathTooLongException) 
{ 
} 
catch (NotSupportedException) 
{ 
} 

if (!bOk) 
{ 
    // ... 
} 
else 
{ 
    // ... 
} 
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
user1102001
  • 689
  • 2
  • 10
  • 21
0

That depends on what you are doing exactly. If it is just a filename you are validating then this will work. The framework function will check for the invalid filename characters for your specific operating system, and will get updated along with the .NET framework. Whereas your regex will not.

Although, if you would want to check if it is a valid path, then there is some more you have to do I guess. Like is it a valid drive letter, path, folder, etc.

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100