C # Read the serial number of the USB flash drive

Source: Internet
Author: User

CodeI searched from the Internet and modified it because the operation was unsuccessful.

Private List < String > _ Serialnumber =   New List < String > ();

///   <Summary>
/// Call this function to store the serial numbers of all USB flash drives on the machine to _ 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.