How To Write an IsValidPath Function
October 12th, 2007
A common requirement that you may encounter is to have a way to validate a string to determine if it’s in the proper format for a path. While there are .NET functions that you can use that will tell you if a given path exists on the disk there is no built-in .NET function that will tell you if a path string has a valid format. This was the subject of a recent discussion on VBForums. In this article, we’ll look at the function I built and some other related ideas that were suggested.
Our Requirements
For this example, we want to create a function that will tell us if the path entered by a user is a valid path string or not. We aren’t concerned about it already existing on the disk or if we have the rights to create the folder. We only want to make sure that the path string has a valid format.
What Won’t Work
We can’t use methods that check the disk for existence of the folder because we don’t need it to actually exist yet. This means we can’t use the Directory.Exists functions from the IO Namespace or the My.Computer.FileSystem Namespace. Some other IO.Path functions, such as IsPathRooted (which was my first suggestion) and GetDirectoryName weren’t well suited for validating path names.
We could use a folder browser or the textbox file system autocomplete feature. However, this wouldn’t fulfill our validation requirement.
Two other methods were thought of by forumites were to create the directory temporarily and capture exceptions. The folder would be deleted if it wasn’t used. The problem here are the performance killing exceptions and the risk of leaving junk on a user’s drive. The second was to use System.IO.Path.GetFullPath. This method worked OK in some cases but had its own formatting quirks plus it required exception trapping to deal with incorrectly formatted paths.
Solving the Problem With Regular Expressions
The way I ended up suggesting to deal with the problem was to use regular expressions. Here is the function:
Private Function IsValidPath(ByVal pathString As String) As Boolean Const PathPattern As String = "^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$" Dim Results As Boolean Try If System.Text.RegularExpressions.Regex.IsMatch(pathString , PathPattern) Then If IO.Path.GetPathRoot(pathString).Length >= 248 Then Results = False Else 'additional checks could go here if desired Results = True End If Else Results = False End If Catch ex As Exception Results = False End Try Return Results End Function
In this function you’ll notice that I first define a string constant with the regular expression string. I’ve ran several tests with it and it seems to work right but if you throw something at it that it can’t handle correctly, please let me know. Next, we look for a match between the pattern and the passed in string.
After passing the first test there is a second one. We need to determine if the path is too long. Windows paths can’t be longer that 247 characters. If this value is exceeded, a False value is return. Notice that there is room to add additional checks if you need them. For example, you could add a check for a local hard drive vs. a network or removable drive.
To call this function, you would just need to call it from the TextChanged event of the target textbox.
That’s my solution. I want to thank VBForum members stimbo, techgnome TokersBall_CDXX, penguin5000, VBDT, and JuggaloBrotha who participated in this discussion and rjbudz who got the whole thing started. If you have an idea or question on this function, please leave a comment here or in the VBForum thread linked at the top of the article.
Entry Filed under: Code Examples
Rate This Article:










3 Comments Add your own
1. Oudknoei | October 12th, 2007 at 3:25 pm
Minor error in the sample code. The first param to the Regex.IsMatch function should be pathString and not Textbox1.Text.
2. jfrankcarr | October 12th, 2007 at 3:53 pm
Thanks Oudknoei
I’ve corrected it.
With the new code formatting I’m using it’s a little harder to proofread the raw HTML. I’ve got to watch my cut-and-paste closer. Thanks again.
3. Sergio | February 11th, 2008 at 7:38 am
PathPattern don’t work
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed