在 C# 中獲取所有磁碟


首先,使用 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:\

更新於: 22-06-2020

580 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.