Read USB Device Serial number in C#

荒凉一梦 提交于 2019-11-30 01:01:29

Try this:

USBSerialNumber usb = new USBSerialNumber();
string serial = usb.getSerialNumberFromDriveLetter("f:\");
MessageBox.Show(serial);

Here's the internals for the USBSerialNumber class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace USBDriveSerialNumber {
    public class USBSerialNumber {

        string _serialNumber;
        string _driveLetter;

        public string getSerialNumberFromDriveLetter(string driveLetter) {
            this._driveLetter = driveLetter.ToUpper();

            if(!this._driveLetter.Contains(":")) {
                this._driveLetter += ":";
            }

            matchDriveLetterWithSerial();

            return this._serialNumber;
        }

        private void matchDriveLetterWithSerial() {

            string[] diskArray;
            string driveNumber;
            string driveLetter;

            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher1.Get()) {
                diskArray = null;
                driveLetter = getValueInQuotes(dm["Dependent"].ToString());
                diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                driveNumber = diskArray[0].Remove(0, 6).Trim();
                if(driveLetter==this._driveLetter){
                    /* This is where we get the drive serial */
                    ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                    foreach (ManagementObject disk in disks.Get()) {

                        if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB") {
                            this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
                        }
                    }
                }
            }
        }

        private string parseSerialFromDeviceID(string deviceId) {
            string[] splitDeviceId = deviceId.Split('\\');
            string[] serialArray;
            string serial;
            int arrayLen = splitDeviceId.Length-1;

                serialArray = splitDeviceId[arrayLen].Split('&');
                serial = serialArray[0];

            return serial;
        }

        private string getValueInQuotes(string inValue) {
            string parsedValue = "";

            int posFoundStart = 0;
            int posFoundEnd = 0;

            posFoundStart = inValue.IndexOf("\"");
            posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);

            parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);

            return parsedValue;
        }

    }
}

Source: http://www.cfdan.com/posts/Retrieving_Non-Volatile_USB_Serial_Number_Using_C_Sharp.cfm

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<ManagementObject>();
        var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive").Get().Cast<ManagementObject>();
        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);

Matt answer is almost right, but you must pass drive letter without back slash in function: string serial = usb.getSerialNumberFromDriveLetter("f:");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!