Uディスク情報の読み取り方法

7982 ワード

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;

        }