Home>
using system.management;
private list<string>_serialnumber=new list<string>();
///<summary>
///Call this function to store all the serial numbers of the USB disk in _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;
}

Calling method:

matchdriveletterwithserial ();
string [] aa=_serialnumber.toarray ();
for (int i=0;i<aa.length;i ++)
{
  aa [i] .tostring ();//Here you can get the serial number of all USB flash drives
}
c
  • Previous Two ways to determine the type prefix of CSS browsers with JavaScript
  • Next Java get network type method