How to retrieve logical drive info in C#

By FoxLearn 12/25/2024 9:02:56 AM   20
In this post, I'll share a simple method using C# to gather basic information about your computer's logical drives.

1. Retrieving Drive Information using Management Classes

The first example will demonstrate how to gather drive information using ManagementScope, ManagementObjectSearcher, ObjectQuery, ManagementObjectCollection, and DirectoryInfo classes.

using System.Management;
using System.IO;

ManagementScope ms = new ManagementScope();
ObjectQuery oq = new ObjectQuery("SELECT DeviceID, VolumeName FROM Win32_LogicalDisk");
ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq);

foreach (ManagementObject mo in mos.Get())
{
    string deviceId = mo["DeviceID"]?.ToString();
    if (string.IsNullOrEmpty(deviceId)) continue;  // Skip if DeviceID is null or empty
    
    DirectoryInfo newDI = new DirectoryInfo(deviceId);
    newDI.Refresh(); // Refresh to ensure directory info is up to date

    // Access FileSystemInfo directly without using GetFiles (which may be redundant if you need only general info)
    FileSystemInfo[] fileSystemInfos = newDI.GetFileSystemInfos();
    
    // Access or display details from "fileSystemInfos" array
    foreach (var fileInfo in fileSystemInfos)
    {
        Console.WriteLine($"File or Directory: {fileInfo.FullName}, Type: {fileInfo.GetType().Name}");
    }
}

In this code snippet, we use System.Management and System.IO namespaces to interact with the system. The key part of the code is the ObjectQuery, where we run an SQL-like query to retrieve information about logical drives.

The query SELECT DeviceID, VolumeName FROM Win32_LogicalDisk fetches all logical drives. If you're interested only in removable disks, you can filter the results using a WHERE clause like this:

SELECT DeviceID, VolumeName FROM Win32_LogicalDisk WHERE DriveType = 2

Here, DriveType is a property of the Win32_LogicalDisk class, and the value 2 represents removable disks (such as USB drives).

2. Using DriveInfo Class to Retrieve Information

If you don’t need to filter by drive type and want a simple way to retrieve information from all drives, the DriveInfo class is an excellent option.

using System.IO;

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("Drive type: {0}", d.DriveType);
}

This code uses the DriveInfo.GetDrives() method to get all the drives on your system. It then prints the drive name and its type to the console.