Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a filename in c# [duplicate]

Tags:

c#

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.

like image 700
Running Rabbit Avatar asked Jul 30 '12 08:07

Running Rabbit


3 Answers

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.

like image 70
ChrisF Avatar answered Oct 03 '22 12:10

ChrisF


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.

like image 43
Steve Avatar answered Oct 03 '22 11:10

Steve


Try this:

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

if (!bOk) 
{ 
    // ... 
} 
else 
{ 
    // ... 
} 
like image 44
user1102001 Avatar answered Oct 03 '22 12:10

user1102001