欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-09 10:21:35
本文实例讲述了c#获取u盘序列号的方法。分享给大家供大家参考。具体如下: using system.management; private list

本文实例讲述了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#程序设计有所帮助。