views:

119

answers:

1

Hello,

I trying to check if the user-inputted string is a valid install destination, then check if it exists, and create it if not. My problem is with validating that the destination string is formatted properly.

I am currently using IO.Directory.Exists( String path ) and works fine except when the user did not format the string properly. That method will return false, but I won't be able to create the folder afterwards.

Googling suggested I use regular expressions to check if the format is proper. I have 0 experience with regular expressions, and am wondering if that will work. Here's what I found:

Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" );
return r.IsMatch( path );

Would this, in combination with Directory.Exists(), give me a good enough method to check if the path is valid and it exists? I know this will vary with OS and other factors, but the program is targeted for Windows users only.

Of course, if there is a simpler solution please do tell!

Thanks!

+3  A: 

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

SLaks
I knew there was something simpler!And thanks, I did not think of the paths-being-relative problem.
Dinoo
Thanks SLaks. I've seen many duplicates, and done many Google searches (on more than one occasion), but this is the first time I've seen a good answer to this particular question.
Robert Harvey