日期:2014-05-18  浏览次数:21307 次

求助 c# 怎样获取u盘序列号
c#获取u盘的序列号,就是想唯一认定U盘,怎么实现呢?谢谢各位了!

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace USBSNTest
{
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;
}


}


  最后,调用方法如下:


USBSerialNumber usbSN = new USBSerialNumber();
textBox3.Text = usbSN.getSerialNumberFromDriveLetter("I");//I为我机器上的U盘盘符,可以自己定义,但是一定要是机器上正在运转的U盘哦 

相关资料更多>