ZetCode

C# DriveInfo

最后修改于 2025 年 4 月 20 日

本教程讲解如何在 C# 中使用 DriveInfo 类来检索计算机上驱动器的信息。DriveInfo 提供了属性和方法来查询驱动器特征。

DriveInfo 类提供有关驱动器的信息,例如名称、类型、可用空间和格式。 它是 System.IO 命名空间的一部分。

DriveInfo 对于需要监视磁盘空间或检查驱动器可用性的应用程序非常有用。 它可以检测可移动驱动器和网络共享。

基本的 DriveInfo 示例

此示例演示如何获取有关系统上所有驱动器的基本信息。 它列出了每个驱动器的名称、类型和可用空间。

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();
        }
    }
}

GetDrives 方法返回 DriveInfo 对象数组。 每个对象代表计算机上的一个驱动器。 该示例在访问需要它的属性之前检查驱动器是否已准备就绪。

IsReady 属性对于可能不可用的可移动驱动器非常重要。 对于已准备好的驱动器,它会显示格式、可用空间和总大小。 空间值从字节转换为千兆字节,以提高可读性。

检查驱动器可用性

此示例展示了如何检查特定驱动器是否可用并准备好访问。 它演示了驱动器操作的正确错误处理。

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}");
        }
    }
}

该示例为 C: 驱动器创建一个 DriveInfo 对象。 它使用 try-catch 来处理访问驱动器属性时可能发生的异常。 IsReady 属性检查驱动器是否可访问。

如果驱动器已准备就绪,它会显示可用空间(以字节为单位)。 该示例展示了正确的错误处理,这在使用可能不可用或受保护的驱动器时至关重要。 这种模式对于健壮的应用程序非常有用。

监视磁盘空间

此示例演示如何监视磁盘空间并在可用空间低于阈值时发出警告。 这对于磁盘空间管理应用程序非常有用。

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!");
            }
        }
    }
}

该示例设置了一个 10GB 的警告阈值并检查 C: 驱动器的可用空间。 它计算已用空间百分比,以便进行更详细的监视。 空间值转换为千兆字节,以提高可读性。

如果可用空间低于阈值,它会显示一条警告消息。 这种方法对于需要最小磁盘空间的系统监视工具或应用程序非常有用。 这些计算使用浮点除法来获得精确的百分比。

使用可移动驱动器

此示例展示了如何检测和使用可移动驱动器,例如 USB 闪存驱动器。 它演示了如何处理可能并非始终准备好的驱动器。

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}");
                }
            }
        }
    }
}

该示例按 DriveType.Removable 过滤驱动器,以查找 USB 驱动器或其他可移动媒体。 它包括针对可能处于不稳定状态的可移动驱动器的其他错误处理。 VolumeLabel 属性显示驱动器的名称(如果可用)。

对于准备就绪的驱动器,它以兆字节为单位显示标签、格式和可用空间。 该示例演示了对可移动媒体的健壮处理,这些媒体可能会在程序运行时插入或移除。 这对于 USB 驱动器管理应用程序至关重要。

获取驱动器卷信息

此示例演示如何检索详细的卷信息,包括卷标和文件系统格式。 它展示了对可选属性的正确 null 检查。

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");
        }
    }
}

该示例展示了如何访问卷标,卷标对于某些驱动器可能为 null。 null 合并运算符 (??) 提供默认值。 RootDirectory 属性返回驱动器根目录的 DirectoryInfo 对象。

它显示 TotalFreeSpaceAvailableFreeSpace,它们在具有磁盘配额的系统上可能有所不同。 所有空间值都转换为兆字节,以保持一致性。 这提供了驱动器属性的全面视图。

查找网络驱动器

此示例演示如何识别和使用网络驱动器。 它展示了网络驱动器访问和性能的特殊注意事项。

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}");
                }
            }
        }
    }
}

该示例按 DriveType.Network 过滤驱动器,以查找映射的网络共享。 它包括针对与网络相关的 IO 异常的特定错误处理。 网络驱动器可能具有更长的响应时间或临时不可用。

对于准备就绪的网络驱动器,它显示映射的路径(卷标)和可用空间。 该示例展示了如何优雅地处理可能暂时不可用的网络驱动器。 这对于企业应用程序非常重要。

检查驱动器格式兼容性

此示例展示了如何检查驱动器是否使用特定的文件系统格式。 它演示了比较驱动器格式以进行兼容性检查。

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");
            }
        }
    }
}

该示例检查驱动器 D: 是否使用 NTFS 或 exFAT 格式。 它对驱动器格式进行不区分大小写的比较,以对照允许的格式。 Array.Exists 方法简化了兼容性检查。

此技术对于需要特定文件系统功能的应用程序非常有用。 该示例可以扩展为处理更多格式或提供格式转换建议。 它演示了实际的格式检查。

来源

DriveInfo 类文档

本教程介绍了在 C# 中使用 DriveInfo 处理驱动器,包括基本信息、空间监视和特殊驱动器类型。

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程