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

时间:2022-06-01 21:55:36

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
}

调用方法:

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

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