方法1:使用Environment
//獲取當前計算機邏輯磁盤名稱列表 String[] drives = Environment.GetLogicalDrives(); Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
方法2:使用DriveInfo可以獲取比較詳細信息
1.命名空間
using System.IO;
2.獲取代碼
/// <summary> /// 測試磁盤信息 /// </summary> static void TestDriveInfo() { DriveInfo[] allDirves = DriveInfo.GetDrives(); //檢索計算機上的所有邏輯驅動器名稱 foreach (DriveInfo item in allDirves) { //Fixed 硬盤 //Removable 可移動存儲設備,如軟盤驅動器或USB閃存驅動器。 Console.Write(item.Name + "---" + item.DriveType); if (item.IsReady) { Console.Write(",容量:"+item.TotalSize+",可用空間大小:"+item.TotalFreeSpace); } else { Console.Write("沒有就緒"); } Console.WriteLine(); } }
注意:IsReady---//磁盤必須准備好,否則讀到光驅就為准備就緒而出錯
字段說明:
Name : 盤符 ,例如:"C:\"
TotalFreeSpace: 返回磁盤可用空間,返回值類型long。
DriveType : 磁盤類型 返回值如下:CDRom(光驅)、Fixed(固定磁盤)、Unknown(未知磁盤)、Network(網絡磁盤)、NoRootDirectory(盤符不存在)、Ram(虛擬磁盤)、Removable(可移動磁盤)。
IsReady : 獲取一個指示驅動器是否已准備好的值 返回bool類型。
RootDirectory : 獲取驅動器根目錄。
TotalSize : 空間總大小。
VolumeLabel : 獲取驅動器卷標,返回string類型。
DriveFormat : 獲取文件系統的名稱,例如 NTFS 或 FAT32
測試結果: