Computer drive information in C#: fetch the drive"s root directory and folders

There"s a range of computer drive information we can fetch programmatically in C#. One type of data is the drive"s root directory. With that we fetch subdirectory information and can even copy, move, or delete a drive"s folders. Let"s see how.

IN THIS ARTICLE:

  • Fetch drive information and root directories in C#
  • Properties and methods of a drive"s root directory in C#
  • Example: get all directories from a particular computer drive
  • Example: search computer folders with a certain name
  • Summary
# Fetch drive information and root directories in C#

We get drive information in C# with the DriveInfo class from the System.IO namespace (Asad & Ali, 2017; Stephens, 2014). A DriveInfo instance represents a single computer drive, and that object has several properties for all kinds of drive information. To get a DriveInfo object we either call the DriveInfo() constructor or the DriveInfo.GetDrives() method.

With a DriveInfo object we can access various properties to fetch drive information. That makes it possible to check the drive"s free space or get or set the drive"s volume label. An interesting property is RootDirectory, which returns a DirectoryInfo object that represents that drive"s root directory (Stephens, 2014). With that property we can fetch all kinds of folder information from a particular drive.

Here"s a quick example of how we can access a drive"s root directory through RootDirectory:

// Create a DriveInfo instance for C:\ DriveInfo cDrive = new DriveInfo("C"); // Look up some root directory information Console.WriteLine("Name: " + cDrive.RootDirectory.FullName); Console.WriteLine("Creation time: " + cDrive.RootDirectory.CreationTimeUtc); Console.WriteLine("Last access time: " + cDrive.RootDirectory.LastAccessTimeUtc);

We first make an instance of the C:\ drive with the DriveInfo() constructor. Then we look up that drive"s root directory information through its RootDirectory property, like its name and the creation and last access time.

The console output of the above code snippet is:

Name: C:\ Creation time: 14-7-2009 2:38:56 Last access time: 10-10-2018 17:40:28 # Properties and methods of a drive"s root directory in C#

What a drive"s RootDirectory property does is return a DirectoryInfo object for the computer drive"s root folder (Stephens, 2014; Microsoft Docs, n.d. a). That DirectoryInfo object has several properties and methods for directory-related operations. With those properties we fetch directory information, like access times, names, and paths. And the DirectoryInfo methods make it possible to copy, move, enumerate, rename, create, and delete directories.

Here are some of the most useful DirectoryInfo members for when we work with a computer drive"s RootDirectory property (Microsoft Docs, n.d. b; Stephens, 2014):

DirectoryInfo memberDescription
AttributesGets or sets the directory attributes. This is a combination of FileAttributes flags with values like Archive, Directory, Hidden, Normal, ReadOnly, System, and Temporary.
CreateSubDirectory()Creates a subdirectory within the directory and then returns a DirectoryInfo object of that new directory. The path of this new subdirectory is relative to the DirectoryInfo object"s directory, but can contain intermediate subdirectories.
CreationTimeGets or sets the directory"s creation time.
CreationTimeUtcGets or sets the directory"s creation time in UTC.
EnumerateDirectories()Returns an enumerable collection with directory information that optionally matches a search pattern. (This method does not recursively search through subdirectories.)
FullNameReturns the full path of the directory.
GetDirectories()Returns an array of DirectoryInfo objects that represent the directory"s subdirectories that optionally matches a search pattern. (This method does not recursively search through subdirectories.)
GetFiles()Returns an array of FileInfo objects that represent the file in the directory that optionally matches a search pattern. (This method does not recursively search through subdirectories.)
GetFileSystemInfos()Returns an array of FileSystemInfo objects that represent subdirectories inside the directory. Those array elements are DirectoryInfo and FileInfo objects (which both inherit from FileSystemInfo). With an optional argument we specify a search pattern. (This method does not recursively search through subdirectories.)
LastAccessTimeGets or sets the directory"s last access time.
LastAccessTimeUtcGets or sets the directory"s last access time in UTC.
LastWriteTimeGets or sets the directory"s last write time.
LastWriteTimeUtcGets of sets the directory"s last write time in UTC.
Refresh()Refreshes the DirectoryInfo object"s data, which makes its properties return up-to-date information.
# Example: get all directories from a particular computer drive

Let"s see how we can use the above properties and methods when we work with a computer drive. One application of the RootDirectory property of the DriveInfo class is to get all top-level directories a particular computer drive has.

The following C# example console application shows how to do that:

using System; using System.IO; class Kodify_Example { static void Main() { DriveInfo cDrive = new DriveInfo("C"); Console.WriteLine("Directories of '{0}':", cDrive.Name); Console.WriteLine("\n{0,-30}\t{1}", "Folder", "Last write time"); Console.WriteLine("---------------------------------------------------"); foreach (DirectoryInfo folder in cDrive.RootDirectory.EnumerateDirectories()) { Console.WriteLine("{0,-30}\t{1}", folder.Name, folder.LastWriteTime.ToString("HH:mm d-M-yy")); } Console.WriteLine("\nPress a key to close this window.."); Console.ReadKey(); } }

The output of this example application is a list of drive folders and their last write time. For my C:\ drive that looks like:

Directories of "C:\": Folder Last write time --------------------------------------------------- $Recycle.Bin 18:28 24-7-13 AHK 10:29 18-6-17 Apps 17:26 23-11-17 Config.Msi 05:55 16-11-17 Documents and Settings 07:08 14-7-09 Go 20:39 12-9-17 Hugo 12:44 20-10-17 MSOCache 19:59 23-7-13 Online backups 06:12 21-11-17 PDFs 14:12 23-11-17 PerfLogs 08:13 14-11-17 Program Files 14:12 19-11-17 Program Files (x86) 11:26 14-11-17 ProgramData 05:45 29-11-17 Recovery 19:03 23-7-13 System Volume Information 16:06 28-11-17 Temp 16:39 26-11-17 Users 18:39 21-7-16 Windows 06:37 16-11-17 Press a key to close this window..

Now let"s walk through the code and see what it does. First we make an instance of the DriveInfo class:

DriveInfo cDrive = new DriveInfo("C");

Here we pass the "C" letter to the DriveInfo() constructor. That creates a DriveInfo instance for the C:\ drive. (This can also trigger an exception when that drive letter doesn"t exist, so you might need to change this for your computer.)

Next we print a legend with the Console.WriteLine() method:

Console.WriteLine("\n{0,-30}\t{1}", "Folder", "Last write time"); Console.WriteLine("---------------------------------------------------");

Then we loop through all directories on the C:\ drive:

foreach (DirectoryInfo folder in cDrive.RootDirectory.EnumerateDirectories()) { Console.WriteLine("{0,-30}\t{1}", folder.Name, folder.LastWriteTime.ToString("HH:mm d-M-yy")); }

With this foreach loop we go through all folders that EnumerateDirectories() returns. We call that method on the RootDirectory property of our computer drive (cDrive.RootDirectory). This loop makes the folder DirectoryInfo looping variable. During each pass through the loop, that variable represents the current folder from the collection returned by EnumerateDirectories().

Inside the loop we output folder information with the Console.WriteLine() method. The data we print are the folder"s name (folder.Name) and its last write time (folder.LastWriteTime). We format that latter with ToString() to have it show hours, minutes, with the day, month, and year with two numbers.

The DirectoryInfo class has two methods that retrieve a list of folders from its directory: GetDirectories() and EnumerateDirectories() (Microsoft Docs, n.d. b). Both these methods return the same subdirectories.

However, EnumerateDirectories() is a better choice when we loop through a huge directory structure. That"s because EnumerateDirectories() starts enumerating directories before all of them have been retrieved, while GetDirectories() doesn"t move forward until it retrieved all directories (Asad & Ali, 2017).

# Example: search computer folders with a certain name

There"s much more we can do with a drive"s RootDirectory property than just go through its first-level subdirectories. When we for instance fetch all computer drives with the DriveInfo.GetDrives() method, and then access the RootDirectory property of each drive, we can search all computer drives for a particular directory.

Here"s how that looks in a console application program:

using System; using System.IO; class Kodify_Example { static void Main() { Console.WriteLine("Searching for all folders with 'a' in their name:"); Console.WriteLine("\n{0,-30}\t{1}", "Folder", "Last access time (UTC)"); Console.WriteLine(new String('-', 60)); // For each of the computer's drives.. foreach (DriveInfo drive in DriveInfo.GetDrives()) { // Try to search through the folders, // looking for one with an 'a' in its name try { foreach (DirectoryInfo folder in drive.RootDirectory.EnumerateDirectories("*a*")) { Console.WriteLine("{0,-30}\t{1}", folder.FullName, folder.LastAccessTimeUtc.ToString("HH:mm d-M-yy")); } } // Don't crash when our program tries to access a folder // it hasn't permission for. Just continue with the other folders. catch (UnauthorizedAccessException unAuth) { Console.WriteLine(unAuth.Message); } } Console.WriteLine("\nPress a key to close this window.."); Console.ReadKey(); } }

The example program lists all top-level folders in a drive"s root directory that have an ‘a’ in them. Here"s what the output looks on my computer:

Searching for all folders with "a" in their name: Folder Last access time (UTC) ------------------------------------------------------------ C:\AHK 08:29 18-6-17 C:\Apps 07:53 29-11-17 C:\Documents and Settings 05:08 14-7-09 C:\MSOCache 17:59 23-7-13 C:\Online backups 05:12 21-11-17 C:\Program Files 07:00 29-11-17 C:\Program Files (x86) 10:26 14-11-17 C:\ProgramData 04:45 29-11-17 C:\System Volume Information 15:06 28-11-17 D:\Site images 06:03 17-2-16 D:\Learning 14:11 7-6-17 D:\Manual backups 05:41 8-8-17 D:\System Volume Information 14:25 21-1-12 E:\System Volume Information 23:00 12-5-16 Press a key to close this window..

The program"s essence is the following foreach loop, where we search for ‘a’ folders:

foreach (DriveInfo drive in DriveInfo.GetDrives()) { try { foreach (DirectoryInfo folder in drive.RootDirectory.EnumerateDirectories("*a*")) { Console.WriteLine("{0,-30}\t{1}", folder.FullName, folder.LastAccessTimeUtc.ToString("HH:mm d-M-yy")); } } catch (UnauthorizedAccessException unAuth) { Console.WriteLine(unAuth.Message); } }

This foreach loop iterates through all computer drives found by the DriveInfo.GetDrives() method. The drive DriveInfo variable represents a single computer drive during each pass through the loop.

The loop"s body consists out of a try/catch code block. In the try portion we cycle through each drive"s first-level subdirectories with the EnumerateDirectories() method (called on the drive"s RootDirectory property). To look for folders with an ‘a’ in their name, we use the "*a*" search pattern. This use of the * wildcard character searches for directories that have any character (or none) before or after the ‘a’ letter. This way it doesn"t matter where ‘a’ appears in the folder name.

We use another foreach loop to iterate through the search results returned by EnumerateDirectories(). With the folder DirectoryInfo looping variable we represent a single folder during each loop cycle. In the loop itself we print the folder"s complete name (folder.FullName) and last access time (folder.LastAccessTime) with the Console.WriteLine() method.

Should our application not have access to a certain directory, then the the EnumerateDirectories() method triggers an UnauthorizedAccessException exception (Microsoft Docs, n.d. c). To prevent that from crashing our program we have a catch code block handle those exceptions by printing their error message to the console window. That way we can see which directories the program couldn"t read while it continues with the folders it can access.

# Summary

To access computer drive information we make an instance of the DriveInfo class. After that we can use that object"s RootDirectory property to access the drive"s root folder. That property returns a DirectoryInfo object, which returns directory information through several properties. And with its methods we can enumerate, copy, delete, and move directories.

The two DirectoryInfo methods that retrieve a list of folders from its directory are GetDirectories() and EnumerateDirectories(). Both return the same first-level subdirectories, but EnumerateDirectories() starts enumerating quicker when we have a huge directory structure. By default both methods return all subdirectories. But with a search pattern as method argument they look for folders that match the pattern.

References

Asad, A. & Ali, H. (2017). The C# Programmer"s Study Guide (MCSD). New York, NY: Apress.

Microsoft Docs (n.d. a). DriveInfo Class. Retrieved on November 9, 2017, from https://docs.microsoft.com/en-us/dotnet/api/system.io.driveinfo?view=netframework-4.7.1

Microsoft Docs (n.d. b). DirectoryInfo Class. Retrieved on November 29, 2017, from https://docs.microsoft.com/en-us/dotnet/api/system.io.directoryinfo?view=netframework-4.7.1

Microsoft Docs (n.d. c). DirectoryInfo.EnumerateDirectories Method. Retrieved on November 29, 2017, from https://docs.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.enumeratedirectories?view=netframework-4.7.1#System_IO_DirectoryInfo_EnumerateDirectories_System_String_System_IO_SearchOption_

Stephens, R. (2014). C# 5.0 Programmer Reference. Indianapolis, IN: John Wiley & Sons.

Last updated on December 1, 2018 (published December 30, 2017).
# Related C# tutorials
  • How do total and available free space of a C# computer drive differ?

    C#‘s DriveInfo class has two similar properties: AvailableFreeSpace and TotalFreeSpace. The first accounts for disk quotas while the second does not.

  • How to check with C# code if a computer drive is ready to access?

    We fetch computer drive info with C#‘s DriveInfo class. Some data requires a ready drive. The IsReady property says whether a drive is ready or not.

  • Get drive information in C# with the DriveInfo class

    We access computer drive information in C# with a DriveInfo object. We use the DriveInfo() constructor or the DriveInfo.GetDrives() method for that.

  • How to get and change a computer drive"s volume label with C#?

    C# can change a drive"s volume label. For that we first make an instance of the DriveInfo class. Then we update that drive"s VolumeLabel property.

  • Calculate a computer drive"s free space with C# code

    We fetch computer disk info with C#‘s DriveInfo class. This tutorial calculates disk spaces in percentage, MB, and GB with that class’ properties.

« All C# computer drives articles

Related: Maybe you are interested (Free: cafelandsaigon)


Related: Maybe you are interested (Free: suribaby)


Related: Maybe you are interested (kistigris)


Related: Maybe you are interested (maithai)


Related: Maybe you are interested (hoangvominh)


Related: Maybe you are interested (3limited)


Related: Maybe you are interested (eletrônicos)


Address: 79E Vo Noo - Singapore - Email: info@dangtinraovatmienphi.us - Phone: 818.333.007 - Website: dangtinraovatmienphi.us
Copyright © 2007 - Noos. All rights reserved