在 C# 中读取 USB 设备序列号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1176053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:04:28  来源:igfitidea点击:

Read USB Device Serial number in C#

c#visual-studio-2005usb-drive

提问by rahul

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

有没有办法使用visual studio 2005读取USB中的文本文件中的USB设备序列号和数据?

采纳答案by The Matt

Try this:

尝试这个:

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

Here's the internals for the USBSerialNumber class:

这是 USBSerialNumber 类的内部结构:

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

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

回答by xarizmat

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);

回答by mr_squall

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

马特答案几乎是正确的,但您必须在函数中传递驱动器号而不带反斜杠: string serial = usb.getSerialNumberFromDriveLetter(" f:");