Validate a filename

  • Thread starter Thread starter Nick Carter
  • Start date Start date
N

Nick Carter

I have a TextBox which a user enters a filename into. What's the simplest
way to validate the input to ensure that the filename is a valid filename
(in other words that it is just a good name as opposed to whether it exists
or not) ?

Nick Carter
 
I have a TextBox which a user enters a filename into. What's the simplest
way to validate the input to ensure that the filename is a valid filename
(in other words that it is just a good name as opposed to whether it exists
or not) ?

Why not use the OpenFileDialog class? This way they could simply pick a
file and you won't have to verify if it exists.
 
You can check to see if the filename contains any of the characters in
Path.InvalidPathChars.
 
Joe White said:
You can check to see if the filename contains any of the characters in
Path.InvalidPathChars.

"C::::::::::::\\\\\\\:::::::" is not a valid pathname too even if it does
only consist of valid caracters.

;-)
 
Patrick,

I do use an OpenFileDialog but I also provide a TextBox.

1) Make the textbox read-only (no typing)

or

2) Use System.IO.File.Exsits() to see if the file exists.
 
"C::::::::::::\\\\\\\:::::::" is not a valid pathname too even if it does
only consist of valid caracters.

<grin> True. And neither is "C:\Windows\System32\User32.dll" -- it's a
perfectly valid filename, but it points to a file that's locked by the
OS, so you can't write to it.

The only foolproof way to validate a filename is to try to create the
file, and then catch any exceptions. But you can't do that ahead of
time to check whether the filename is valid, because depending on
permissions, you might not be able to delete the test file you just
created...
 
Back
Top