Method for obtaining U disk serial number by C
- 2021-08-12 03:22:08
- OfStack
In this paper, an example is given to describe the method of obtaining the serial number of U disk by C #. Share it for your reference. The details are as follows:
using System.Management;
private List<string> _serialNumber = new List<string>();
/// <summary>
/// Call this function to set all native U The disk serial number is stored to _serialNumber Medium
/// </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;
}
Invoke the method:
matchDriveLetterWithSerial();
string[] aa = _serialNumber.ToArray();
for (int i = 0; i < aa.Length; i++)
{
aa[i].ToString(); // You can take out all the things you have now here U Disk serial number
}
I hope this article is helpful to everyone's C # programming.