ZetCode

C# DriveInfo

last modified April 20, 2025

This tutorial explains how to use the DriveInfo class in C# to retrieve information about drives on a computer. DriveInfo provides properties and methods to query drive characteristics.

The DriveInfo class provides information about drives such as name, type, available free space, and format. It is part of the System.IO namespace.

DriveInfo is useful for applications that need to monitor disk space or check drive availability. It can detect removable drives and network shares.

Basic DriveInfo Example

This example demonstrates how to get basic information about all drives on the system. It lists each drive's name, type, and available free space.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo drive in allDrives)
        {
            Console.WriteLine($"Drive: {drive.Name}");
            Console.WriteLine($"Type: {drive.DriveType}");

            if (drive.IsReady)
            {
                Console.WriteLine($"Format: {drive.DriveFormat}");
                Console.WriteLine($"Free space: {drive.AvailableFreeSpace / (1024 * 1024 * 1024)} GB");
                Console.WriteLine($"Total size: {drive.TotalSize / (1024 * 1024 * 1024)} GB");
            }
            Console.WriteLine();
        }
    }
}

The GetDrives method returns an array of DriveInfo objects. Each object represents a drive on the computer. The example checks if the drive is ready before accessing properties that require it.

The IsReady property is important for removable drives that might not be available. For ready drives, it displays the format, free space, and total size. The space values are converted from bytes to gigabytes for better readability.

Checking Drive Availability

This example shows how to check if a specific drive is available and ready for access. It demonstrates proper error handling for drive operations.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            DriveInfo drive = new DriveInfo("C");
            
            if (drive.IsReady)
            {
                Console.WriteLine($"Drive {drive.Name} is ready");
                Console.WriteLine($"Free space: {drive.AvailableFreeSpace} bytes");
            }
            else
            {
                Console.WriteLine($"Drive {drive.Name} is not ready");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error accessing drive: {ex.Message}");
        }
    }
}

The example creates a DriveInfo object for the C: drive. It uses try-catch to handle potential exceptions when accessing drive properties. The IsReady property checks if the drive is accessible.

If the drive is ready, it displays the available free space in bytes. The example shows proper error handling which is crucial when working with drives that might be unavailable or protected. This pattern is useful for robust applications.

Monitoring Drive Space

This example demonstrates how to monitor drive space and warn when free space falls below a threshold. It's useful for disk space management applications.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        const long warningThreshold = 10 * 1024 * 1024 * 1024; // 10GB
        
        DriveInfo drive = new DriveInfo("C");
        
        if (drive.IsReady)
        {
            double freeSpaceGB = drive.AvailableFreeSpace / (1024.0 * 1024 * 1024);
            double totalSpaceGB = drive.TotalSize / (1024.0 * 1024 * 1024);
            double usedPercentage = 100 - (freeSpaceGB / totalSpaceGB * 100);
            
            Console.WriteLine($"Drive {drive.Name}");
            Console.WriteLine($"Free space: {freeSpaceGB:0.00} GB");
            Console.WriteLine($"Used space: {usedPercentage:0.00}%");
            
            if (drive.AvailableFreeSpace < warningThreshold)
            {
                Console.WriteLine("WARNING: Low disk space!");
            }
        }
    }
}

The example sets a warning threshold of 10GB and checks the C: drive's available space. It calculates the used space percentage for more detailed monitoring. The space values are converted to gigabytes for better readability.

If the available space falls below the threshold, it displays a warning message. This approach is useful for system monitoring tools or applications that require minimum disk space. The calculations use floating-point division for precise percentages.

Working with Removable Drives

This example shows how to detect and work with removable drives like USB flash drives. It demonstrates handling drives that may not always be ready.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        DriveInfo[] drives = DriveInfo.GetDrives();
        
        foreach (DriveInfo drive in drives)
        {
            if (drive.DriveType == DriveType.Removable)
            {
                Console.WriteLine($"Found removable drive: {drive.Name}");
                
                try
                {
                    if (drive.IsReady)
                    {
                        Console.WriteLine($"Label: {drive.VolumeLabel}");
                        Console.WriteLine($"Format: {drive.DriveFormat}");
                        Console.WriteLine($"Free space: {drive.AvailableFreeSpace / (1024 * 1024)} MB");
                    }
                    else
                    {
                        Console.WriteLine("Drive is not ready (no media inserted?)");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error accessing drive: {ex.Message}");
                }
            }
        }
    }
}

The example filters drives by DriveType.Removable to find USB drives or other removable media. It includes additional error handling for removable drives that might be in an unstable state. The VolumeLabel property shows the drive's name if available.

For ready drives, it displays the label, format, and free space in megabytes. The example demonstrates robust handling of removable media that might be inserted or removed while the program runs. This is essential for USB drive management applications.

Getting Drive Volume Information

This example demonstrates how to retrieve detailed volume information including the volume label and file system format. It shows proper null checking for optional properties.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        DriveInfo drive = new DriveInfo("C");
        
        if (drive.IsReady)
        {
            Console.WriteLine($"Drive: {drive.Name}");
            Console.WriteLine($"Volume label: {drive.VolumeLabel ?? "[None]"}");
            Console.WriteLine($"File system: {drive.DriveFormat}");
            Console.WriteLine($"Root directory: {drive.RootDirectory.FullName}");
            
            Console.WriteLine("\nAdditional properties:");
            Console.WriteLine($"Total free space: {drive.TotalFreeSpace / (1024 * 1024)} MB");
            Console.WriteLine($"Available free space: {drive.AvailableFreeSpace / (1024 * 1024)} MB");
            Console.WriteLine($"Total size: {drive.TotalSize / (1024 * 1024)} MB");
        }
    }
}

The example shows how to access the volume label, which might be null for some drives. The null-coalescing operator (??) provides a default value. The RootDirectory property returns a DirectoryInfo object for the drive's root.

It displays both TotalFreeSpace and AvailableFreeSpace which may differ on systems with disk quotas. All space values are converted to megabytes for consistency. This provides a comprehensive view of drive properties.

Finding Network Drives

This example demonstrates how to identify and work with network drives. It shows special considerations for network drive access and performance.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        DriveInfo[] drives = DriveInfo.GetDrives();
        
        foreach (DriveInfo drive in drives)
        {
            if (drive.DriveType == DriveType.Network)
            {
                Console.WriteLine($"Network drive: {drive.Name}");
                
                try
                {
                    if (drive.IsReady)
                    {
                        Console.WriteLine($"Mapped to: {drive.VolumeLabel}");
                        Console.WriteLine($"Free space: {drive.AvailableFreeSpace / (1024 * 1024)} MB");
                    }
                    else
                    {
                        Console.WriteLine("Network drive is not available");
                    }
                }
                catch (IOException ex)
                {
                    Console.WriteLine($"Network error: {ex.Message}");
                }
            }
        }
    }
}

The example filters drives by DriveType.Network to find mapped network shares. It includes specific error handling for network-related IO exceptions. Network drives may have longer response times or temporary unavailability.

For ready network drives, it displays the mapped path (volume label) and available space. The example shows how to gracefully handle network drives that might be temporarily unavailable. This is important for enterprise applications.

Checking Drive Format Compatibility

This example shows how to check if a drive uses a specific file system format. It demonstrates comparing drive formats for compatibility checking.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string[] requiredFormats = { "NTFS", "exFAT" };
        DriveInfo drive = new DriveInfo("D");
        
        if (drive.IsReady)
        {
            Console.WriteLine($"Drive {drive.Name} format: {drive.DriveFormat}");
            
            bool compatible = Array.Exists(requiredFormats, 
                f =>  f.Equals(drive.DriveFormat, StringComparison.OrdinalIgnoreCase));
            
            if (compatible)
            {
                Console.WriteLine("Drive format is compatible");
            }
            else
            {
                Console.WriteLine("WARNING: Incompatible drive format");
            }
        }
    }
}

The example checks if drive D: uses either NTFS or exFAT format. It performs a case-insensitive comparison of the drive format against allowed formats. The Array.Exists method simplifies the compatibility check.

This technique is useful for applications that require specific file system features. The example could be extended to handle more formats or provide format conversion suggestions. It demonstrates practical format checking.

Source

DriveInfo Class Documentation

This tutorial covered working with drives in C# using DriveInfo, including basic information, space monitoring, and special drive types.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.