C# DriveInfo.GetDrives():获取所有逻辑驱动器的DriveInfo对象

  • Post category:C#

DriveInfo.GetDrives()方法是C#中的一个静态方法,用于获取系统中可用的驱动器。

GetDrives()方法的作用

DriveInfo.GetDrives()方法用于获取系统中所有的驱动器,并且返回一个DriveInfo对象数组。该方法返回的DriveInfo对象包含驱动器的名称、类型、格式、总容量、可用容量以及是否已准备好等信息。

GetDrives()方法的使用方法

首先,需要导入System.IO命名空间:

using System.IO;

然后,调用DriveInfo.GetDrives()方法获取系统中的所有驱动器:

DriveInfo[] drives = DriveInfo.GetDrives();

此时,变量drives便保存了系统中所有可用的驱动器。

我们可以使用foreach循环遍历所有的驱动器:

foreach (DriveInfo drive in drives)
{
    Console.WriteLine("驱动器名称: " + drive.Name);
    Console.WriteLine("驱动器类型: " + drive.DriveType);
    Console.WriteLine("驱动器格式: " + drive.DriveFormat);
    Console.WriteLine("驱动器总容量: " + drive.TotalSize);
    Console.WriteLine("驱动器可用容量: " + drive.AvailableFreeSpace);
    Console.WriteLine("驱动器是否准备好: " + drive.IsReady);
    Console.WriteLine("");
}

输出结果如下:

驱动器名称: C:\
驱动器类型: Fixed
驱动器格式: NTFS
驱动器总容量: 524060299264
驱动器可用容量: 221222897920
驱动器是否准备好: True

驱动器名称: D:\
驱动器类型: Fixed
驱动器格式: NTFS
驱动器总容量: 524060299264
驱动器可用容量: 83954212864
驱动器是否准备好: True

驱动器名称: E:\
驱动器类型: CD-ROM
驱动器格式: 
驱动器总容量: 0
驱动器可用容量: 0
驱动器是否准备好: False

示例说明

以下两个示例说明了DriveInfo.GetDrives()方法的使用场景:

  1. 检查某个文件是否位于可移动磁盘中:
bool IsFileInRemovableDrive(string filePath)
{
    DriveInfo[] drives = DriveInfo.GetDrives();
    FileInfo fileInfo = new FileInfo(filePath);

    foreach (DriveInfo drive in drives)
    {
        if (drive.DriveType == DriveType.Removable && 
            fileInfo.Directory.Root.FullName.ToLower() == drive.RootDirectory.FullName.ToLower())
        {
            return true;
        }
    }

    return false;
}
  1. 获取所有可用的磁盘,并将其展示在TreeView控件中:
void FillTreeView()
{
    treeView1.Nodes.Clear();

    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in drives)
    {
        if (drive.IsReady)
        {
            TreeNode driveNode = new TreeNode(drive.Name);
            treeView1.Nodes.Add(driveNode);

            DirectoryInfo root = drive.RootDirectory;
            DirectoryInfo[] subDirectories = root.GetDirectories();
            foreach (DirectoryInfo directory in subDirectories)
            {
                TreeNode directoryNode = new TreeNode(directory.Name);
                driveNode.Nodes.Add(directoryNode);

                FillTreeViewNode(directoryNode, directory);
            }
        }
    }
}

void FillTreeViewNode(TreeNode node, DirectoryInfo directory)
{
    try
    {
        DirectoryInfo[] subDirectories = directory.GetDirectories();
        foreach (DirectoryInfo subDirectory in subDirectories)
        {
            TreeNode subDirectoryNode = new TreeNode(subDirectory.Name);
            node.Nodes.Add(subDirectoryNode);

            FillTreeViewNode(subDirectoryNode, subDirectory);
        }
    }
    catch
    {
        // ignore
    }
}