在 C# 中获取所有驱动器

csharpprogrammingserver side programming更新于 2025/5/23 14:37:17

首先,使用 GetDrives 获取所有驱动器的名称 −

var drv = DriveInfo.GetDrives();

循环获取系统上所有驱动器的名称 −

foreach (DriveInfo dInfo in drv) {
   Console.WriteLine(dInfo.Name);
}

让我们看看完整的代码 −

示例

using System;
using System.Linq;
using System.IO;
public class Demo {
   public static void Main() {
      var drv = DriveInfo.GetDrives();
      foreach (DriveInfo dInfo in drv) {
         Console.WriteLine(dInfo.Name);
      }
   }
}

输出

/etc/resolv.conf
/etc/hostname
/etc/hosts
/run/secrets
/home/cg/root

注意:结果会因操作系统不同而有所不同。以上输出显示在 Linux 操作系统上。

它将在 Windows 操作系统上产生以下结果:

C:\
D:\
E:\

相关文章