The System.IO.Directory class exposes all the members you need to manipulate folders. Because the Directory class belongs to the System.IO namespace, you must import the IO namespace into any project that might require the Directory object’s members with the following statement:
Imports System.IOCode language: CSS (css)
The Directory object exposes methods for accessing folders and their contents, which are described in the subtopics below.
This method creates a new folder, whose path is passed to the method as a string argument:
Directory.CreateDirectory(path)Code language: CSS (css)
path is the path of the folder you want to create and can be either an absolute or a relative path. If it’s a relative path, its absolute value is determined by the current drive and path (use the GetCurrentDirectory method to find out the absolute current path). The CreateDirectory method returns a DirectoryInfo object, which contains information about the newly created folder. The DirectoryInfo object is discussed later in this chapter, along with the FileInfo object. Notice that the CreateDirectory method can create multiple nested folders in a single call. The following statement will create the folder folder1 (if it doesn’t exist), folder2 (if it doesn’t exist) under folder1, and finally folder3 under folder2 in the C: drive:
If folder1 exists already, but it doesn’t contain a subfolder named folder2, then folder2 will be automatically created. An exception will be thrown if the total path is too long or if your application doesn’t have permission to create a folder in the specified path. However, no exception will be thrown if the specified path already exists on the disk. The method will simply not create any new folders. It will still return a DirectoryInfo object, which describes the existing folder.
This method deletes a folder and all the files in it. If the folder contains subfolders, the Delete method will optionally remove the entire directory tree under the node you’re removing. The simplest form of the Delete method accepts as an argument the path of the folder to be deleted:
Directory.Delete(path)Code language: CSS (css)
This method will delete the specified path only. If the specified folder contains subfolders, they will not be deleted and, therefore, the specified folder won’t be deleted, either. To delete a folder recursively (that is, also delete any subfolders under it), use the following form of the Delete method, which accepts a second argument:
Directory.Delete(path, recursive)Code language: CSS (css)
The recursive argument is a True/False value. Set it to True to delete recursively the subfolders under the specified folder. This method deletes folders permanently (it doesn’t send them to the Recycle Bin).
The statements in Listing 11.1 attempt to delete a single folder. If the folder contains subfolders, the Delete method will fail, and the structured exception handler will be activated. The exception handler examines the type of the exception, and if it was caused because the folder isn’t empty, the exception handler prompts the user about whether it should delete the contents of the folder. If the user gives permission to delete the folder’s contents, the code calls the second form of the Delete method, forcing it to delete the folder recursively.
Listing 11.1: Deleting a Directory
Private Sub bttnDelete Click(...) Handles bttnDelete.Click
Catch exc As IOException
If exc.Message.IndexOf( _
"The directory is not empty") > -1 Then
Dim reply As MsgBoxResult
reply = MsgBox( _
"Delete all files and subfolders?", _
MsgBoxStyle.YesNo, "Directory Not Empty")
If reply = MsgBoxResult.Yes Then
Catch ex As Exception
MsgBox("Failed to delete folder" & vbCrLf & _
End SubCode language: PHP (php)
Notice the nested Try. . .Catch statement that catches unauthorized exceptions (you may not have the rights to delete the specific folder).
This method accepts a path as an argument and returns a True/False value indicating whether the specified folder exists:
Directory.Exists(path)Code language: CSS (css)
The Delete method will throw an exception if you attempt to delete a folder that doesn’t exist, so you can use the Exists method to make sure the folder exists before attempting to delete it:
If Directory.Exists(path) Then Directory.Delete(path)Code language: CSS (css)
This method moves an entire folder to another location in the file system; its syntax is the following, where source is the name of the folder to be moved and destination is the name of the destination folder:
Directory.Move(source, destination)Code language: CSS (css)
The Move method doesn’t work along different volumes, and the destination can’t be the same as the source argument, obviously.
Notice the lack of a Copy method that would copy an entire folder to a different location. To copy a folder, you must manually create an identical folder structure and then copy the corresponding files to the proper subfolders. The FileSystem component provides a MoveFile and a MoveFolder method, which move a single file and an entire folder, respectively.
Use these methods to retrieve and set the path of the current directory. The current directory is a basic concept when working with files. This is the folder in which all files specified by name will be saved and where the application will look for files specified by their name, not their complete path. Also, relative paths are resolved according to their relation to the current directory. By default, the GetCurrentDirectory method returns the folder in which the application is running. SetCurrentDirectory accepts a string argument, which is a path, and sets the current directory to the specified path. You can change the current folder by specifying an absolute or a relative path, such as the following:
The two periods are a shortcut for the parent folder. From the application folder, we move up to the parent folder and then to the Resources folder under the application’s folder. This is where any resources (such as images and sounds) used by the application are stored. Notice that the value you pass to the SetCurrentDirectory method as an argument must be the name of an existing folder. If not, a DirectoryNotFoundException exception will be thrown. You can also switch to a folder on another drive if you specify the full folder’s path, including its drive letter.
If you’re working on a new project that hasn’t been saved yet, the current directory is the application’s folder (WindowsApplication1 or something similar) under the Temporary Projects folders.
This method returns the root part of the path passed as argument, and its syntax is the following:
root = Directory.GetDirectoryRoot(path)
The path argument is a string, and the return value is also a string, such as C:\ or D:\. Notice that the GetDirectoryRoot method doesn’t require that the path argument exists. It will return the name of the root folder of the specified path.
This method retrieves all the subfolders of a specific folder and returns their names as an array of strings:
Dim Dirs() As String
The path argument is the path of the folder whose subfolders you want to retrieve. Another form of the GetDirectories method allows you to specify search criteria for the folders you want to retrieve, and its syntax is the following:
Dirs = Directory.GetDirectories(path, pattern)
This statement returns an array of strings with the names of the subfolders that match the search criteria. To retrieve all the subfolders of the C:\Windows folder with the string System in their names, use the following statement:
This statement will go through the subfolders of C:\WINDOWS and return those that contain the string SYSTEM (including System32 and MySystem). The only special characters you can use in the criteria specification are the question mark, which stands for any single character, and the asterisk, which stands for any string. Listing 11.2 retrieves the names of the folders that contain the string System under the C:\WINDOWS folder and prints them in the Output window.
Listing 11.2: Retrieving Selected Subfolders of a Folder
Dim Dirs() As String
Dirs = Directory.GetDirectories("C:\WINDOWS", "*SYSTEM*")
Dim dir As String
Debug.WriteLine(Dirs.Length & " folders match the pattern ’*SYSTEM*’ ")
For Each dir In Dirs
The GetDirectories method doesn’t work recursively; it returns the subfolders of the specified folder, but not their subfolders.
This method returns the names of the files in the specified folder as an array of strings. The syntax of the GetFiles method is the following, where path is the path of the folder whose files you want to retrieve and files is an array of strings that’s filled with the names of the files:
Another form of the GetFiles method allows you to specify a pattern and retrieve only the names of the files that match the pattern. This form of the method accepts a second argument, which is a string similar to the pattern argument of the GetDirectories method:
The statements in Listing 11.3 retrieve all the .exe files under the C:\WINDOWS folder and print their names in the Output window.
Listing 11.3: Retrieving Selected Files of a Folder
Dim files() As String
files = Directory.GetFiles("C:\WINDOWS", "*.EXE")
MsgBox("Found " & files.Length & " EXE files")
Dim file As String
For Each file In files
This method returns an array of all items (files and folders) in a path. The simplest form of the method is
items = Directory.GetFileSystemEntries(path)
where items is an array of strings. As with the GetFiles method, you can specify a second argument, which filters the entries you want to retrieve. To iterate through the items of a folder, use a loop such as the following:
Dim itm As String
For Each itm In Directory.GetFileSystemEntries("C:\windows")
Because the GetFileSystemEntries method returns an array of strings, use the Exists method of the Directory object to distinguish between folders and files. The File object, which is equivalent to the Directory object and is discussed in the following section, also exposes an Exists method. The loop shown in Listing 11.4 goes through the file system items in the C:\Program Files folder and displays their names, along with the indication FOLDER or FILE, depending on the type of each item.
Listing 11.4: Retrieving the File System Items of a Folder
Dim items() As String
Dim path As String = "c:\Program Files"
items = Directory.GetFileSystemEntries(path)
Dim itm As String
For Each itm In items
If Directory.Exists(itm) Then
Debug.WriteLine("FOLDER " & itm)
Debug.WriteLine("FILE " & itm)
NextCode language: PHP (php)
If you execute these statements, you will see a list such as the following in the Output window (only considerably longer):
FOLDER c:\Program Files\Microsoft.NET
FOLDER c:\Program Files\HTML Help Workshop
FOLDER c:\Program Files\Microsoft Web Controls 0.6
FILE c:\Program Files\folder.htt
FILE c:\Program Files\desktop.iniCode language: CSS (css)
The My.Computer.FileSystem component doesn’t expose a method to retrieve folders and files at once. Instead, you must use the GetFiles and GetDirectories methods to retrieve either the files or the folders under a specific folder.
These methods read or set the date that a specific folder was created. The GetCreationTime method accepts a path as an argument and returns a Date value:
Dim CreatedOn As Date
SetCreationTime accepts a path and a date value as arguments and sets the specified folder’s creation time to the value specified by the second argument:
Directory.SetCreationTime(path, datetime)Code language: CSS (css)
These two methods are equivalent to the GetCreationTime and SetCreationTime methods, except they return and set the most recent date and time that the file was accessed. The most common reason to change the last access time for a file is so that the specific file will be excluded from a routine that deletes old files or to include it in a list of backup files (with an automated procedure that backs up only the files that have been changed since their last backup).
These two methods are equivalent to the GetCreationTime and SetCreationTime methods, but they return and set the most recent date and time the file was written to.
This method returns an array of strings, which are the names of the logical drives on the computer. The statements in Listing 11.5 print the names of all logical drives.
Listing 11.5: Retrieving the Names of All Drives on the Computer
Dim drives() As String
drives = Directory.GetLogicalDrives
Dim drive As String
For Each drive In drives
When executed, these statements will produce a list such as the following:
Notice that the GetLogicalDrives method doesn’t return any floppy drives, unless there’s a disk inserted into the drive.
This method returns a DirectoryInfo object that represents the properties of a folder’s parent folder. The syntax of the GetParent method is as follows:
Dim parent As DirectoryInfo = Directory.GetParent(path)Code language: PHP (php)
The name of the parent folder, for example, is parent.Name, and its full name is parent.FullName.