ZetCode

C# DriveInfo

last modified November 6, 2026

In this article we show how to get information about drives with the DriveInfo class in C#.

DriveInfo from the System.IO namespace describes a drive: its name, type, file system format, volume label, and size and free space. On Windows a drive is a drive letter such as C:\. On Linux and macOS there are no drive letters; DriveInfo represents the mount points of the system, so the root file system, the boot partition, and many virtual file systems all appear as drives.

The outputs in this article come from Linux.

Listing drives

The GetDrives method returns all drives of the computer.

Program.cs
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    string format = drive.IsReady ? drive.DriveFormat : "-";
    Console.WriteLine($"{drive.Name,-28} {drive.DriveType,-10} {format}");
}

We print the name, type, and file system format of each drive.

string format = drive.IsReady ? drive.DriveFormat : "-";

The IsReady property tells whether the drive can be read. An optical drive without a disc or a disconnected network share is not ready, and reading its format, label, or size throws an IOException. The Name and DriveType properties are always available.

DriveType is an enumeration with the values Unknown, NoRootDirectory, Removable, Fixed, Network, CDRom, and Ram. On Linux, the type is derived from the file system: sysfs, proc, and tmpfs mounts are reported as Ram, and snap packages mounted as squashfs images are Fixed. The output below is shortened; this machine reports 54 drives.

$ dotnet run
/sys                         Ram        sysfs
/proc                        Ram        proc
/dev                         Ram        devtmpfs
/dev/pts                     Ram        devpts
/run                         Ram        tmpfs
/                            Fixed      ext4
/sys/kernel/security         Ram        securityfs
...
/snap/bare/5                 Fixed      squashfs
/boot/efi                    Removable  vfat
...
/run/user/1000/gvfs          Ram        fuse.gvfsd-fuse
/run/user/1000/doc           Ram        fuse.portal

Drive properties

A DriveInfo object can be created for a drive name. Here we take the root of the current directory.

Program.cs
string root = Path.GetPathRoot(Environment.CurrentDirectory)!;
var drive = new DriveInfo(root);

Console.WriteLine($"Name: {drive.Name}");
Console.WriteLine($"DriveType: {drive.DriveType}");
Console.WriteLine($"IsReady: {drive.IsReady}");
Console.WriteLine($"DriveFormat: {drive.DriveFormat}");
Console.WriteLine($"VolumeLabel: {drive.VolumeLabel}");
Console.WriteLine($"RootDirectory: {drive.RootDirectory.FullName}");
Console.WriteLine($"TotalSize: {ToGiB(drive.TotalSize)}");
Console.WriteLine($"TotalFreeSpace: {ToGiB(drive.TotalFreeSpace)}");
Console.WriteLine($"AvailableFreeSpace: {ToGiB(drive.AvailableFreeSpace)}");

static string ToGiB(long bytes) => $"{bytes / (1024.0 * 1024 * 1024):F2} GiB";

We print all properties of the drive.

string root = Path.GetPathRoot(Environment.CurrentDirectory)!;
var drive = new DriveInfo(root);

Path.GetPathRoot returns C:\ on Windows and / on Unix. On Windows, the constructor also accepts a drive letter alone, such as "C".

Console.WriteLine($"TotalSize: {ToGiB(drive.TotalSize)}");
Console.WriteLine($"TotalFreeSpace: {ToGiB(drive.TotalFreeSpace)}");
Console.WriteLine($"AvailableFreeSpace: {ToGiB(drive.AvailableFreeSpace)}");

The sizes are in bytes, so we convert them to gibibytes. TotalFreeSpace is all free space on the drive, while AvailableFreeSpace is the space the current user may use. The values differ when disk quotas are in effect, and on Linux ext4 file systems reserve about 5% of the blocks for the root user. Use AvailableFreeSpace to decide whether a file will fit.

On Linux, VolumeLabel returns the mount point rather than the file system label.

$ dotnet run
Name: /
DriveType: Fixed
IsReady: True
DriveFormat: ext4
VolumeLabel: /
RootDirectory: /
TotalSize: 456.89 GiB
TotalFreeSpace: 75.03 GiB
AvailableFreeSpace: 51.76 GiB

Checking free space

An application that writes large files can check the free space before starting.

Program.cs
const long threshold = 10L * 1024 * 1024 * 1024;

string root = Path.GetPathRoot(Environment.CurrentDirectory)!;
var drive = new DriveInfo(root);

double usedPercent = 100.0 * (drive.TotalSize - drive.AvailableFreeSpace) / drive.TotalSize;
long availableGiB = drive.AvailableFreeSpace / (1024 * 1024 * 1024);

Console.WriteLine($"{drive.Name}: {usedPercent:F1}% used, {availableGiB} GiB available");

if (drive.AvailableFreeSpace < threshold)
{
    Console.WriteLine("warning: less than 10 GiB available");
}
else
{
    Console.WriteLine("enough free space");
}

We print the used space as a percentage and warn when less than 10 GiB is available.

const long threshold = 10L * 1024 * 1024 * 1024;

The L suffix is necessary. Without it the multiplication is done with int values and 10 GiB does not fit in an int.

double usedPercent = 100.0 * (drive.TotalSize - drive.AvailableFreeSpace) / drive.TotalSize;

Starting the calculation with 100.0 makes it a floating-point division.

$ dotnet run
/: 88.7% used, 51 GiB available
enough free space

Integer overflow in size constants

The next program defines the threshold without the L suffix.

Program.cs
const long threshold = 10 * 1024 * 1024 * 1024;
Console.WriteLine(threshold);

Because all operands are constants, the compiler evaluates the expression and reports the overflow as an error. With variables instead of constants the overflow happens silently at run time and gives a wrong value.

$ dotnet run overflow.cs
overflow.cs(1,24): error CS0220: The operation overflows at compile time in checked mode
The build failed. Fix the build errors and run again.

Filtering drives

LINQ queries help to work with the long list of drives found on Unix systems.

Program.cs
DriveInfo[] drives = DriveInfo.GetDrives();

foreach (var group in drives.GroupBy(d => d.DriveType).OrderBy(g => g.Key))
{
    Console.WriteLine($"{group.Key}: {group.Count()}");
}

Console.WriteLine();

const long minSize = 100L * 1024 * 1024;

var storage = drives
    .Where(d => d.DriveType is DriveType.Fixed or DriveType.Removable or DriveType.Network)
    .Where(d => d.IsReady && d.AvailableFreeSpace > minSize);

foreach (DriveInfo d in storage)
{
    long freeMiB = d.AvailableFreeSpace / (1024 * 1024);
    Console.WriteLine($"{d.Name,-40} {d.DriveType,-10} {d.DriveFormat,-6} {freeMiB,8} MiB free");
}

We count the drives of each type and then list only the drives that store data.

foreach (var group in drives.GroupBy(d => d.DriveType).OrderBy(g => g.Key))

GroupBy groups the drives by their type.

.Where(d => d.DriveType is DriveType.Fixed or DriveType.Removable or DriveType.Network)
.Where(d => d.IsReady && d.AvailableFreeSpace > minSize)

We keep fixed, removable, and network drives, and skip those with less than 100 MiB of available space. This removes the read-only snap images and small virtual file systems. The IsReady check comes first, so the free space is read only from ready drives. On this machine, the EFI system partition is reported as removable.

$ dotnet run
Removable: 1
Fixed: 31
Network: 2
Ram: 20

/                                        Fixed      ext4      52996 MiB free
/var/snap/firefox/common/host-hunspell   Fixed      ext4      52996 MiB free
/boot/efi                                Removable  vfat        504 MiB free

Finding the drive of a path

On Windows the drive of a path is given by its root, for example C:\. On Unix a path belongs to the mount point that is its longest prefix.

Program.cs
DriveInfo[] drives = DriveInfo.GetDrives();

Show("temp", Path.GetTempPath());
Show("home", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Show("current", Environment.CurrentDirectory);

void Show(string label, string path)
{
    string full = Path.GetFullPath(path);

    DriveInfo? drive = drives
        .Where(d => full.StartsWith(d.RootDirectory.FullName, StringComparison.OrdinalIgnoreCase))
        .MaxBy(d => d.RootDirectory.FullName.Length);

    Console.WriteLine($"{label}: {drive?.Name} ({drive?.DriveFormat})");
}

We find the drive for the temporary directory, the home directory, and the current directory.

DriveInfo? drive = drives
    .Where(d => full.StartsWith(d.RootDirectory.FullName, StringComparison.OrdinalIgnoreCase))
    .MaxBy(d => d.RootDirectory.FullName.Length);

From the drives whose root directory is a prefix of the path, we take the one with the longest root. This works on Windows too, where the drive letter is the only match. The simple prefix test would also match /run for a path starting with /runner; production code should compare whole path segments.

On Linux, new DriveInfo(path) accepts any directory, but it does not look up the mount point; the Name property simply returns the given path.

$ dotnet run
temp: / (ext4)
home: / (ext4)
current: / (ext4)

Missing drives

Creating a DriveInfo object for a missing drive does not throw. Accessing its size does.

Program.cs
Show("C");
Show("/no/such/mount");

try
{
    new DriveInfo("");
}
catch (ArgumentException e)
{
    Console.WriteLine($"ArgumentException: {e.Message}");
}

static void Show(string name)
{
    var drive = new DriveInfo(name);
    Console.WriteLine($"{drive.Name}: IsReady={drive.IsReady}, DriveType={drive.DriveType}");

    try
    {
        Console.WriteLine(drive.TotalSize);
    }
    catch (DriveNotFoundException e)
    {
        Console.WriteLine($"{e.GetType().Name}: {e.Message}");
    }
}

We query a Windows drive letter, which does not exist on Linux, and a path that is not mounted.

Console.WriteLine($"{drive.Name}: IsReady={drive.IsReady}, DriveType={drive.DriveType}");

For a missing drive IsReady is false and the type is NoRootDirectory.

catch (DriveNotFoundException e)

Reading TotalSize throws DriveNotFoundException, which derives from IOException. An empty name throws an ArgumentException already in the constructor.

$ dotnet run
C: IsReady=False, DriveType=NoRootDirectory
DriveNotFoundException: Could not find the drive 'C'. The drive might not be ready or might not be mapped.
/no/such/mount: IsReady=False, DriveType=NoRootDirectory
DriveNotFoundException: Could not find the drive '/no/such/mount'. The drive might not be ready or might not be mapped.
ArgumentException: Drive name must not be empty. (Parameter 'driveName')

Reading all drives safely

A drive that is ready may still refuse access. Code that reads every drive should handle the exceptions per drive.

Program.cs
int ok = 0;

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    try
    {
        if (!drive.IsReady)
        {
            Console.WriteLine($"{drive.Name}: not ready");
            continue;
        }

        _ = drive.TotalSize;
        ok++;
    }
    catch (Exception e) when (e is IOException or UnauthorizedAccessException)
    {
        Console.WriteLine($"{drive.Name}: {e.GetType().Name}");
    }
}

Console.WriteLine($"{ok} drives read successfully");

We try to read the size of each drive and count the successes.

catch (Exception e) when (e is IOException or UnauthorizedAccessException)

The exception filter catches both I/O errors and access errors. On this system, the document portal of the desktop session reports itself as ready, but reading its size throws an UnauthorizedAccessException.

$ dotnet run
/run/user/1000/doc: UnauthorizedAccessException
53 drives read successfully

Platform-specific members

Setting the volume label is supported only on Windows.

Program.cs
var drive = new DriveInfo(Path.GetPathRoot(Environment.CurrentDirectory)!);

if (OperatingSystem.IsWindows())
{
    drive.VolumeLabel = "DATA";
    Console.WriteLine($"label set to {drive.VolumeLabel}");
}
else
{
    Console.WriteLine($"on this platform VolumeLabel is read-only: {drive.VolumeLabel}");
}

We set the label on Windows and only read it elsewhere.

if (OperatingSystem.IsWindows())

The VolumeLabel setter throws PlatformNotSupportedException on other platforms. The platform compatibility analyzer reports the call with warning CA1416, unless it is guarded by an OperatingSystem.IsWindows check. Changing a label also requires administrator rights.

$ dotnet run
on this platform VolumeLabel is read-only: /

Source

DriveInfo class

In this article we have worked with drives in C# using the DriveInfo class.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.