Created
April 27, 2015 05:07
-
-
Save k4m4r82/049a6e7186b7b7ef4c26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sumber : https://social.msdn.microsoft.com/Forums/en-US/923ccb2e-857e-429d-90ae-00f73e32eba4/getting-usb-flash-drive-serial-number-in-c?forum=wdk | |
// tambahkan namespace System.Management | |
public class USBSerialNumber | |
{ | |
string _serialNumber; | |
string _driveLetter; | |
public string getSerialNumberFromDriveLetter(string driveLetter) | |
{ | |
this._driveLetter = driveLetter.ToUpper(); | |
if (!this._driveLetter.Contains(":")) | |
{ | |
this._driveLetter += ":"; | |
} | |
matchDriveLetterWithSerial(); | |
return this._serialNumber; | |
} | |
private void matchDriveLetterWithSerial() | |
{ | |
string[] diskArray; | |
string driveNumber; | |
string driveLetter; | |
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition"); | |
foreach (ManagementObject dm in searcher1.Get()) | |
{ | |
diskArray = null; | |
driveLetter = getValueInQuotes(dm["Dependent"].ToString()); | |
diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(','); | |
driveNumber = diskArray[0].Remove(0, 6).Trim(); | |
if (driveLetter == this._driveLetter) | |
{ | |
/* This is where we get the drive serial */ | |
ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); | |
foreach (ManagementObject disk in disks.Get()) | |
{ | |
if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB") | |
{ | |
this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString()); | |
} | |
} | |
} | |
} | |
} | |
private string parseSerialFromDeviceID(string deviceId) | |
{ | |
string[] splitDeviceId = deviceId.Split('\\'); | |
string[] serialArray; | |
string serial; | |
int arrayLen = splitDeviceId.Length - 1; | |
serialArray = splitDeviceId[arrayLen].Split('&'); | |
serial = serialArray[0]; | |
return serial; | |
} | |
private string getValueInQuotes(string inValue) | |
{ | |
string parsedValue = ""; | |
int posFoundStart = 0; | |
int posFoundEnd = 0; | |
posFoundStart = inValue.IndexOf("\""); | |
posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1); | |
parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1); | |
return parsedValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment