Read USB Device Serial number in C#

前端 未结 3 2126
春和景丽
春和景丽 2020-12-25 10:30

Is there a way to read USB device serial number and data in a text file in USB using visual studio 2005?

3条回答
  •  生来不讨喜
    2020-12-25 10:56

    Or, you can do it with much less code, here's the sample:

            string driveletter = "D:";
    
            var index = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition").Get().Cast();
            var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive").Get().Cast();
            string serial = "";
            try
            {
                var drive = (from i in index where i["Dependent"].ToString().Contains(driveletter) select i).FirstOrDefault();
                var key = drive["Antecedent"].ToString().Split('#')[1].Split(',')[0];
    
                var disk = (from d in disks
                            where
                                d["Name"].ToString() == "\\\\.\\PHYSICALDRIVE" + key &&
                                d["InterfaceType"].ToString() == "USB"
                            select d).FirstOrDefault();
                serial = disk["PNPDeviceID"].ToString().Split('\\').Last();
            }
            catch 
            {
                //drive not found!!
            }
            Response.WriteLine(serial);
    

提交回复
热议问题