Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
Problem
The user has supplied a directory, and you want to confirm that it is valid before accessing it. Solution
Sample code folder: Chapter 12\DirectoryExists Use the My.Computer. FileSystem.DirectoryExists() method to determine whether a directory exists or not. Pass the method a String containing the directory path to check for validity. Discussion
To try out this feature, create a new Windows Forms application, and add a TextBox control named TextBox1 and a Button control named Button1 to the form. Now add the following code to the form's class template: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' ----- Test for a valid directory. If (My.Computer.FileSystem.DirectoryExists( _ TextBox1.Text)) Then MsgBox("The directory already exists.") Else MsgBox("The directory does not exist, " & _ "or is part of an invalid path.") End If End Sub
Figure 12-2 shows this form in use. Figure 12-2. Testing a directory to see if it exists
The DirectoryExists( ) method checks for the actual presence of a directory, not just for a valid directory-name format. It works with three types of drive paths:
URL-based directory paths, using the "file://" prefix, cannot be used with this method or with most of the features in My.Computer.FileSystem. Security restrictions in effect for the current user may prevent access to certain portions of a file system. See Also
Recipe 12.10 shows how to determine if a file exists. |
Категории