How to Get all drives in C#

By FoxLearn 5/6/2024 8:12:44 AM   39
This post shows you How to get all logical drives on a system in C#.

In C#, you can retrieve all drives available in the system using the DriveInfo class from the System.IO namespace.

How to get all drives in C#

Here's a simple example demonstrating how to get all drives.

// Get all drives in the system
DriveInfo[] driveInfos = DriveInfo.GetDrives();

// Iterate through each drive and print its information
foreach (DriveInfo drive in driveInfos)
{
    Console.WriteLine($"Drive: {drive.Name}");
    Console.WriteLine($"Drive Type: {drive.DriveType}");
    if (drive.IsReady)
    {
        Console.WriteLine($"Volume Label: {drive.VolumeLabel}");
        Console.WriteLine($"File System: {drive.DriveFormat}");
        Console.WriteLine($"Total Size: {drive.TotalSize} bytes");
        Console.WriteLine($"Available Free Space: {drive.AvailableFreeSpace} bytes");
    }
}

This code retrieves an array of DriveInfo objects representing all available drives in the system. Then, it iterates through each DriveInfo object and prints information such as drive name, drive type, volume label, file system, total size, and available free space.

// c# get logial drivers
string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
    Console.WriteLine(drive);

You can also use GetLogicalDrives method from the System.IO namespace to retrieve an array driver name, then display the logical drives of the current computer in c#.