博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

读取U盘信息的方法

Posted on 2013-02-22 09:27  Leon zhang  阅读(737)  评论(0编辑  收藏  举报
public class UsbDiskInfo
    {
        public string Display { get; set; }
        public string Value { get; set; }
    }

    public class UsbDiskHelper
    {
        //返回结果大致为:AAGP30PMDRVS56NK
        public static IEnumerable<UsbDiskInfo> GetUsbDisksInfo()
        {
            List<UsbDiskInfo> list = new List<UsbDiskInfo>();
            list.Add(new UsbDiskInfo{Display=DropDownListHelper.PLEASE_CHOOSE, Value=null});
            var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher.Get())
            {
                //dm["Dependent"] 大致为:\\JIANG-PC\root\cimv2:Win32_LogicalDisk.DeviceID="H:"
                string strDriveLetter = GetValueInQuotes(dm["Dependent"].ToString());

                //dm["Antecedent"] 大致为:\\JIANG-PC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #0"
                string[] diskArray = GetValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                string driveNumber = diskArray[0].Remove(0, 6).Trim();
                var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                foreach (ManagementObject disk in disks.Get())
                {
                    //disk["Name"] 大致为:\\.\PHYSICALDRIVE1
                    //disk["InterfaceType"] 大致为:USB
                    if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) && disk["InterfaceType"].ToString() == "USB")
                    {
                        //disk["PNPDeviceID"] 大致为:USBSTOR\DISK&VEN_TECLAST&PROD_COOLFLASH(S)&REV_1100\AAGP30PMDRVS56NK&0
                        list.Add(new UsbDiskInfo { Display = strDriveLetter, Value = ParseSerialFromDeviceId(disk["PNPDeviceID"].ToString()) });
                    }
                }
            }
            return list;
        }

        private static string ParseSerialFromDeviceId(string deviceId)
        {
            var splitDeviceId = deviceId.Split('\\');
            var arrayLen = splitDeviceId.Length - 1;
            var serialArray = splitDeviceId[arrayLen].Split('&');
            var serial = serialArray[0];
            return serial;
        }

        private static string GetValueInQuotes(string inValue)
        {
            var posFoundStart = inValue.IndexOf("\"", StringComparison.Ordinal);
            var posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1, StringComparison.Ordinal);
            var parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);
            return parsedValue;
        }