Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is a valid Windows directory (folder) path

I am trying to determine whether a string input by a user is valid for representing a path to a folder. By valid, I mean formatted properly.

In my application, the folder represents an installation destination. Provided that the folder path is valid, I want to determine if the folder exists, and create it if it does not.

I am currently using IO.Directory.Exists( String path ). I find that this works fine except when the user does not format the string properly. When that happens, this method will return false which indicates that the folder does not exist. But this is a problem because I won't be able to create the folder afterwards.

From my googling I found a suggestion to use a regular expression to check if the format is proper. I have no experience with regular expressions, and am wondering if that is a viable approach. Here's what I found:

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

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

like image 349
Pudpuduk Avatar asked Jun 29 '10 00:06

Pudpuduk


People also ask

How do you check if a string is a path Python?

When you get a string value for a path, you can check if the path represents a file or a directory using Python programming. To check if the path you have is a file or directory, import os module and use isfile() method to check if it is a file, and isdir() method to check if it is a directory.


1 Answers

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

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

like image 174
SLaks Avatar answered Oct 08 '22 10:10

SLaks