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.
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.
Call Path.GetFullPath
; it will throw exceptions if the path is invalid.
To disallow relative paths (such as Word
), call Path.IsPathRooted
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With