gpt4 book ai didi

c# - C#读取USB设备序列号

转载 作者:太空狗 更新时间:2023-10-29 22:25:06 25 4
gpt4 key购买 nike

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

最佳答案

试试这个:

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

这是 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;
}

}
}

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

关于c# - C#读取USB设备序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1176053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com