The .NET Framework includes classes for performing basic file management tasks, including browsing drives, managing files and folders, and responding to changes to the file system. This functionality is vital to applications that allow the user to edit or manage documents, such as word processors or image editors. File management is also a common requirement for system management applications, such as a tool that processes log files.
This tutorial describes the most useful classes for managing the file system, including DriveInfo, DirectoryInfo, and FileSystemWatcher.
At the end of this tutorial, you will be able to.
- Generate a list of drives attached to the computer
- Browse, copy, move, and delete files and folders
- Respond to new or changed files and folders
Download the completed project here: Browse-File-System (Visual Basic.NET).
Using the DriveInfo Class
You can examine hard disks connected to a computer by using the DriveInfo class in the System.IO namespace. First, call the DriveInfo.GetDrives() static method to retrieve a collection of DriveInfo objects. DriveInfo.GetDrives() returns a DriveInfo object for each logical disk attached to the computer, including network drives.
Note: a static method is a method that does not require you to create an instance of the class. In other words, you do not need to create an instance of DriveInfo to call the DriveInfo.GetDrives() static method.
When you create an instance of DriveInfo (either by calling DriveInfo.GetDrives() or by creating a new instance of DriveInfo and specifying the drive letter), you can access the DriveInfo properties:
- AvailableFreeSpace. The amount of free space, in bytes, currently available on the drive.
- TotalFreeSpace. The total free space available on the drive. Typically, you should use AvailableFreeSpace instead.
- TotalSize. The total size of the drive.
- DriveFormat. The format, such as NTFS or FAT32.
- DriveType. The type of the drive, as indicated using the DriveType enumeration. It can be CDRom, Fixed, Unknown, Network, NoRootDirectory, Ram, Removable, or Unknown.
- Name. The name of the drive, such as C:\ or E:\.
- VolumeLabel. The label assigned to the drive.
- RootDirectory. An instance of DirectoryInfo that relates to the root directory. This might not be available, so you should always attempt to catch an exception when accessing this property.
- IsReady. Indicates whether the drive is ready for access.
Using the DirectoryInfo Class
The DirectoryInfo class provides information about directories. You can access a directory on the file system by creating a new instance of DirectoryInfo and specifying the path. Alternatively, you can retrieve the root directory for a drive by creating an instance of DriveInfo and accessing DriveInfo.RootDirectory.
After creating an instance of DirectoryInfo, you can access the following properties:
- Attributes. Returns a FileAttribuates instance, which you can examine to determine if a folder is compressed, encrypted, or marked as archived.
- CreationTime or CreationTimeUtc. The time the folder was created.
- Exists. A Boolean value determining whether the folder exists.
- FullName. The path to the directory.
- LastAccessTime and LastAccessTimeUtc. The time the folder was last accessed.
- LastWriteTime and LastWriteTimeUtc.
- Name. The time the folder was last written to.
- Parent. A DirectoryInfo instance that represents the parent folder.
- Root. A DirectoryInfo instance that represents the root of the path.
You can also call the following members:
- Create. Creates the folder if it does not yet exist.
- CreateSubdirectory. Creates a subdirectory within the current folder.
- Delete. Deletes the current folder.
- GetDirectories. Gets a collection of DirectoryInfo instances representing subdirectories of the current folder.
- GetFiles. Gets a collection of FileInfo instances representing the contents of the folder.
- MoveTo. Moves a folder to the specified destination.
- Refresh. Refreshes the directory information. You might call this to retrieve the latest information about the directory if there is a significant delay between the time you create the instance of DirectoryInfo and the time you access it.
Using the FileInfo Class
The DirectoryInfo class allows you to browse directories. If you want to view the files contained within directories, create an instance of DirectoryInfo, and then call the GetFiles method.
GetFiles returns a collection of FileInfo objects. For example, the following code sample displays the files (but not folders) contained in the C:\Windows directory:
Dim dir As New DirectoryInfo("C:\Windows") For Each fi As FileInfo In dir.GetFiles() Console.WriteLine(fi.Name) Next
If you wanted to also view the folders, you would need to create a For Each loop that iterated through the DirectoryInfo instances returned by the DirectoryInfo.GetDirectories() method.
Managing Files and Folders with Static Methods
Static methods can be called without creating an instance of a class. Consider the previous demonstration, which created an instance of the DirectoryInfo class, and then called DirectoryInfo.GetFiles to retrieve a collection of files within the directory. DirectoryInfo.GetFiles is not a static method, because you had to create an instance of DirectoryInfo call it.
However, the Directory.GetFiles method is static. Therefore, you can call it without creating an instance of the Directory class. Similarly, the File class provides static methods similar to some of those provided by the non-static FileInfo class. There is not a static version of the DriveInfo class.
Using static methods can save you a few lines of code by not requiring you to create an instance of a class. You should be familiar with both static and non-static methods, however.
This code sample demonstrates how few lines of code are required to display the files contained in the C:\Windows folder using static methods. Note that I never create an instance of the Directory class.
For Each file As String In Directory.GetFiles("C:\Windows") Console.WriteLine(file) Next
Browsing Files and Folders
Here’s the transcript to that video:
Let’s create a simple application that browses the available drives on the computer, the folders, and files.
I’ve created a Windows Forms application with three ListBoxes. The first list, driveList, is going to contain a list of all the drives on the computer (like the C: drive, the D: drive, or the E: drive).
When the user clicks one of those drives, it will show all of the folders at the root of that drive. When the user clicks one of those folders, the program will list all of the files contained within that folder.
First, we need to populate the driveList list when the form opens. So, I’m going to double-click the form to open the Form.Load event handler.
First, I need to import the System.IO namespace. This namespace contains all of the classes used for accessing the file system.
Next, I’m going to use a For Each loop within the Form.Load event handler. This loop is going to iterate through the DriveInfo.GetDrives static method. That returns a collection of DriveInfo objects. Each one is going to be named di. As I iterate through each of these, I’m going to add them to the driveList listbox by calling the Items.Add method.
Back to the form, it’s time for me to populate the foldersList list box when the user clicks a drive. I’m going to double-click driveList to open up the default event handler, which handles the SelectedIndexChanged event handler. This event is called any time the user selects a different item.
The first thing I need to do is to clear any items that already exist within the foldersList list box. Next, I’m going to create a try-catch block. This is important here because, if the user selects a drive that is not available, for example, a memory card reader that does not have a memory card inserted into it, it will throw an error. So, in the event handler I’m going to show the error in a MessageBox.
Within the Try block I’ll actually do the work of listing all the sub-folders. First, I’m going to create an instance of the DriveInfo class that corresponds to the drive that the user selected. I’ll call it drive. Now, to retrieve it, I’m going to use the DirectCast method. DirectCast casts, which is another word for converts, a generic object into the type that we actually need. So, to retrieve the selected item I need to call driveList.SelectedItem. Notice that I’m also specifying the class that it needs to be converted into.
With this method here, DirectCast returns an instance of DriveInfo, which is why I can create the new object in this way. For example, if the user clicks the C:\ drive, this will create an instance of DriveInfo that relates to the C:\ drive.
Now I can create a For Each loop that iterates through the Drive.RootDirectory.GetDirectories method, which corresponds to all of the root directories for the drive. Within that For Each loop I need to add each of the DirectoryInfo instances, which I called dirInfo, to the foldersList.
So, the last thing I need to do is to populate the filesList list box whenever the user clicks the foldersList. So, I’ll double-click this to again create a SelectedIndexChanged event handler. As before, the first thing I need to do is to clear the items from the list. Now, I’m going to create a DirectoryInfo instance that relates to the selected directory. As before I’m going to use DirectCast to cast it to a DirectoryInfo instance. And, one last For Each loop. This time, I’m going to iterate through the DirectoryInfo.GetFiles collection, which is a collection of FileInfo objects, and add each one to the filesList listBox.
Now, if I did all this right, I should be able to run it and browse the contents of the C:\ drive. Clicking C:\ loaded the foldersList list box with all the folders in the root of the C:\ drive. I’ll click the Windows folders, and the filesList list box now shows each of the files in my Windows folder.
Return to the .NET Framework Fundamentals Tutorials Table of Contents.