首页 > 编程 > C# > 正文

C#获取U盘序列号的方法

2020-01-24 01:26:29
字体:
来源:转载
供稿:网友

本文实例讲述了C#获取U盘序列号的方法。分享给大家供大家参考。具体如下:

using System.Management;private List<string> _serialNumber = new List<string>();/// <summary>/// 调用这个函数将本机所有U盘序列号存储到_serialNumber中/// </summary>private void matchDriveLetterWithSerial(){  string[] diskArray;  string driveNumber;  var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");  foreach (ManagementObject dm in searcher.Get())  {    getValueInQuotes(dm["Dependent"].ToString());    diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');    driveNumber = diskArray[0].Remove(0, 6).Trim();    var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");    foreach (ManagementObject disk in disks.Get())    {      if (disk["Name"].ToString() == ("////.//PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")      {        _serialNumber.Add(parseSerialFromDeviceID(disk["PNPDeviceID"].ToString()));      }    }  }}private static string parseSerialFromDeviceID(string deviceId){  var splitDeviceId = deviceId.Split('//');  var arrayLen = splitDeviceId.Length - 1;  var serialArray = splitDeviceId[arrayLen].Split('&');  var serial = serialArray[0];  return serial;}private static string getValueInQuotes(string inValue){  var posFoundStart = inValue.IndexOf("/"");  var posFoundEnd = inValue.IndexOf("/"", posFoundStart + 1);  var parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);  return parsedValue;}

调用方法:

matchDriveLetterWithSerial();string[] aa = _serialNumber.ToArray();for (int i = 0; i < aa.Length; i++){  aa[i].ToString(); //这里就可以拿出现在所有的U盘序列号}

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表