Recipe 12.2. Determining if a Directory Exists


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:

  • Absolute paths referenced from a drive letter, as in C:\WINDOWS.

  • Absolute paths referenced through UNC syntax, as in \\system\share\directory.

  • Relative paths referenced from the current directory as understood by the running application, as in ..\AnotherDirectory. You can start the path with the current directory (.) or parent directory (..) indicators, or with the name of a directory assumed to be found in the current directory. Use the My.Computer. FileSystem.CurrentDirectory property to determine or modify the current directory location.

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.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net