Browsing Files and Folders – C#

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 complete project here: Browse-File-System (C#).

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:

DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");

foreach (FileInfo fi in dir.GetFiles())
    Console.WriteLine(fi.Name);

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.

foreach (string file in Directory.GetFiles(@"C:\Windows"))
    Console.WriteLine(file);

Browsing Files and Folders

Watch my video for a description of how to browse files and folders in C#:

Here’s the transcript to that video:

To demonstrate working with the file system, I’ve created a simple Windows Forms application with three listboxes.

The first listbox, driveList, is going to contain a list of drives available on the system. When the user selects one of these drives, the application will populate the foldersList listbox, containing all the subfolders of that particular drive. The third listbox will contain all of the files within that folder.

Note that this isn’t extremely complex; you can’t select subfolders for example. Ideally, it would be implemented with a tree, but I selected this setup for simplicity.

So, the first thing we need to do when the application loads is to populate the driveList list. I will do that in the Form1.Load event handler. Before we do anything, I need to add the System.IO namespace that contains all of the different classes used for accessing the file system.

Within the Form1.Load handler we need to create a foreach loop that iterates through all of the drives and adds them to the drives list. We call DriveInfo.GetDrives. That method returns a collection of DriveInfo objects. Now, we just need to add each object to the driveList listbox.

With that done, we need to populate the foldersList listbox whenever the user selects a drive. So, I will double-click on this to select the SelectedIndexChanged event handler for that listbox. This event handler is called any time the user selects a different item in the list box.

First, we want to clear any items that might already be in the folderList list. So, we will call the Items.Clear method.

I’m going to put all of this into a try-catch block. This will enable me to catch any errors that might occur if the user selects a drive that is not available. For example, a memory card reader that does not have a memory card currently inserted. A simple try-catch block that just displays the error message will suffice for our purposes.

Within the try, I will create a DriveInfo object by casting the selected object from the list. If you look up to the foreach loop, you’ll notice that I added DriveInfo items to the driveList. When the user selects one, I can access that DriveInfo item using drivelist.SelectedItem. However, SelectedItem, as you can see here, returns a generic object item. To be able to access that as the original DriveInfo class, I need to cast it, which I do by putting DriveInfo in parenthesis directly before the SelectedItem. This creates a DriveInfo object named Drive that is the item that was selected up here. So, if the user clicks the C drive, the DriveInstance represents the C:\ drive.

With that extracted, I can create a foreach loop that iterates through the directories within the selected drive. I’m going to iterate through a collection of DirectoryInfo instances and I’m going to access the RootDirectory member of the drive instance I just created, and call GetDirectories. GetDirectories contains a collection of DirectoryInfo objects. Now, I’m going to add those DirectoryInfo objects to the foldersList items.

Now, when the application runs, it will populate the driveList with a list of available drives. When the user selects a drive, it will populate the foldersList with a list of folders within that drive. Now, we need to populate filesList with a list of files within that folder.

As I did before, I’ll double-click to create the foldersList.SelectedIndexChanged event handler. First, I’ll clear any existing items by calling the filesList.Items.Clear() method. Then, I’m going to create a DirectoryInfo instance by casting the selected item to an instance of DirectoryInfo.

Another foreach loop will iterate through the DirectoryInfo.GetFiles collection, which contains all the files in the selected directory. THat provides me a collection of FileInfo objects. Now, I will add each of those to the Items collection in the filesList.

Now, let’s run our application and see if it works. I will click the C:\ drive. It populates the foldersList listbox with a list of folders. Let’s select the Windows folders. You can see that it lists all of the items contained within that folder.

Return to the .NET Framework Fundamentals Tutorials Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>