網上找了很久關于C#檢測移動硬盤并獲取盤符的代碼但沒能找到,所以只能自己解決了
C#獲取所有硬盤
var arr = DriveInfo.GetDrives();
得出的所有磁盤,發現對于移動硬盤,DriveType 不是 Removable 類型,而是 Fixed 枚舉類型。
C#檢測移動硬盤,網上找了很久,沒有現成正確的代碼,只有自己想辦法了。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public static List< string > GetListDisk() { List< string > lstDisk = new List< string >(); ManagementClass mgtCls = new ManagementClass( "Win32_DiskDrive" ); var disks = mgtCls.GetInstances(); foreach (ManagementObject mo in disks) { //if (mo.Properties["InterfaceType"].Value.ToString() != "SCSI" // && mo.Properties["InterfaceType"].Value.ToString() != "USB" // ) // continue; if (mo.Properties[ "MediaType" ].Value == null || mo.Properties[ "MediaType" ].Value.ToString() != "External hard disk media" ) { continue ; } //foreach (var prop in mo.Properties) //{ // Console.WriteLine(prop.Name + "\t" + prop.Value); //} foreach (ManagementObject diskPartition in mo.GetRelated( "Win32_DiskPartition" )) { foreach (ManagementBaseObject disk in diskPartition.GetRelated( "Win32_LogicalDisk" )) { lstDisk.Add(disk.Properties[ "Name" ].Value.ToString()); } } //Console.WriteLine("-------------------------------------------------------------------------------------------"); } return lstDisk; } |
此代碼是通過找 Win32_DiskDrive,Win32_DiskPartition,Win32_LogicalDisk 對應的屬性值的規律, 三個之間的關系 得出 移動硬盤的盤符的。
原文鏈接:http://www.cnblogs.com/lztkdr/p/CSharp_External_Hard_Disk.html