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

Pudpuduk picture Pudpuduk · Jun 29, 2010 · Viewed 129.3k times · Source

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.

Answer

SLaks picture SLaks · Jun 29, 2010

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

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