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:
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:
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 member | Description |
---|---|
Attributes | Gets 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. |
CreationTime | Gets or sets the directory"s creation time. |
CreationTimeUtc | Gets 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.) |
FullName | Returns 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.) |
LastAccessTime | Gets or sets the directory"s last access time. |
LastAccessTimeUtc | Gets or sets the directory"s last access time in UTC. |
LastWriteTime | Gets or sets the directory"s last write time. |
LastWriteTimeUtc | Gets 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. |
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:
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:
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:
Then we loop through all directories on the C:\ drive:
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).
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:
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:
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.
# SummaryTo 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.
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.
C#‘s DriveInfo class has two similar properties: AvailableFreeSpace and TotalFreeSpace. The first accounts for disk quotas while the second does not.
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.
We access computer drive information in C# with a DriveInfo object. We use the DriveInfo() constructor or the DriveInfo.GetDrives() method for that.
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.
We fetch computer disk info with C#‘s DriveInfo class. This tutorial calculates disk spaces in percentage, MB, and GB with that class’ properties.