C#检测获取移动硬盘盘符
最近做一个小工具, C# 对 移动硬盘的检测,
var arr = DriveInfo.GetDrives();
得出的所有磁盘,发现对于移动硬盘,DriveType 不是 Removable 类型,而是 Fixed 枚举类型。
C#检测移动硬盘,网上找了很久,没有现成正确的代码,只有自己想办法了。
代码如下:
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 对应的属性值的规律, 三个之间的关系 得出 移动硬盘的盘符。