如何从C#中的USB闪存驱动器获取VID/PID?
我需要对所有驱动器进行检查,查看是否有任何VID/PID与特定驱动器匹配,如果匹配,我需要获取该闪存驱动器的驱动器号。如何从C#中的USB闪存驱动器获取VID/PID?,c#,usb,pid,usb-flash-drive,C#,Usb,Pid,Usb Flash Drive,我需要对所有驱动器进行检查,查看是否有任何VID/PID与特定驱动器匹配,如果匹配,我需要获取该闪存驱动器的驱动器号。 谢谢大家 WMI应该能够处理此 您必须添加对System.Management dll的引用,并且需要具有: “使用系统管理”行。。。请参阅底部的链接以获取屏幕截图和更详细的解释 using System.Management; // Get all the disk drives ManagementObjectSearcher mosDisks = new Managem
谢谢大家 WMI应该能够处理此 您必须添加对System.Management dll的引用,并且需要具有: “使用系统管理”行。。。请参阅底部的链接以获取屏幕截图和更详细的解释
using System.Management;
// Get all the disk drives
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Add the HDD to the list (use the Model field as the item's caption)
cmbHdd.Items.Add(moDisk["Model"].ToString());
}
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
{
// Get all the disk drives from WMI that match the Model name selected in the ComboBox
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
// Loop through the drives retrieved, although it should normally be only one loop going on here
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Set all the fields to the appropriate values
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
lblModel.Text = "Model: " + moDisk["Model"].ToString();
lblSerial.Text = "Serial: " + moDisk["SerialNumber"].ToString();
lblInterface.Text = "Interface: " + moDisk["InterfaceType"].ToString();
// The capacity in gigabytes is easily calculated
lblCapacity.Text = "Capacity: " + moDisk["Size"].ToString() + " bytes (" + Math.Round(((((double)Convert.ToDouble(moDisk["Size"]) / 1024) / 1024) / 1024), 2) + " GB)";
lblPartitions.Text = "Partitions: " + moDisk["Partitions"].ToString();
lblSignature.Text = "Signature: " + moDisk["Signature"].ToString();
lblFirmware.Text = "Firmware: " + moDisk["FirmwareRevision"].ToString();
lblCylinders.Text = "Cylinders: " + moDisk["TotalCylinders"].ToString();
lblSectors.Text = "Sectors: " + moDisk["TotalSectors"].ToString();
lblHeads.Text = "Heads: " + moDisk["TotalHeads"].ToString();
lblTracks.Text = "Tracks: " + moDisk["TotalTracks"].ToString();
lblBytesPerSect.Text = "Bytes per Sector: " + moDisk["BytesPerSector"].ToString();
lblSectorsPerTrack.Text = "Sectors per Track: " + moDisk["SectorsPerTrack"].ToString();
lblTracksPerCyl.Text = "Tracks per Cylinder: " + moDisk["TracksPerCylinder"].ToString();
}
}
从win32类中,CIM_DiskDrive具有以下参数:
*看起来“DeviceID”就是你想要的
class Win32_DiskDrive : CIM_DiskDrive
{
uint16 Availability;
uint32 BytesPerSector;
uint16 Capabilities[];
string CapabilityDescriptions[];
string Caption;
string CompressionMethod;
uint32 ConfigManagerErrorCode;
boolean ConfigManagerUserConfig;
string CreationClassName;
uint64 DefaultBlockSize;
string Description;
string DeviceID;
boolean ErrorCleared;
string ErrorDescription;
string ErrorMethodology;
string FirmwareRevision;
uint32 Index;
datetime InstallDate;
string InterfaceType;
uint32 LastErrorCode;
string Manufacturer;
uint64 MaxBlockSize;
uint64 MaxMediaSize;
boolean MediaLoaded;
string MediaType;
uint64 MinBlockSize;
string Model;
string Name;
boolean NeedsCleaning;
uint32 NumberOfMediaSupported;
uint32 Partitions;
string PNPDeviceID;
uint16 PowerManagementCapabilities[];
boolean PowerManagementSupported;
uint32 SCSIBus;
uint16 SCSILogicalUnit;
uint16 SCSIPort;
uint16 SCSITargetId;
uint32 SectorsPerTrack;
string SerialNumber;
uint32 Signature;
uint64 Size;
string Status;
uint16 StatusInfo;
string SystemCreationClassName;
string SystemName;
uint64 TotalCylinders;
uint32 TotalHeads;
uint64 TotalSectors;
uint64 TotalTracks;
uint32 TracksPerCylinder;
};
代码的顶部部分取自:
如果您只需要检查设备何时连接,问题就简单多了。您需要检查事件。如果要创建Windows窗体应用程序,可以通过实现接口并将其传递给
应用程序中的函数来完成。如果您不使用表单应用程序,则需要从WndProc派生类并重写WndProc。记住调用,以便将其添加到windows消息队列中
一旦您有了接收DBT_DEVICEARRIVAL
的方法,您就需要解析它。(以下内容不是在IDE中编写的,因此未对其进行测试)
如果您需要枚举所有已连接的设备,我建议使用。如果您想了解如何在不使用WMI的情况下执行此操作,请查看中的代码,它可能会帮助您开始。这是解决OP问题的更好方法,因为WMI完全是一种滥杀滥伤。
public static bool GetDriveVidPid(string szDriveName, ref ushort wVID, ref ushort wPID)
{
bool bResult = false;
string szSerialNumberDevice = null;
ManagementObject oLogicalDisk = new ManagementObject("Win32_LogicalDisk.DeviceID='" + szDriveName.TrimEnd('\\') + "'");
foreach(ManagementObject oDiskPartition in oLogicalDisk.GetRelated("Win32_DiskPartition"))
{
foreach(ManagementObject oDiskDrive in oDiskPartition.GetRelated("Win32_DiskDrive"))
{
string szPNPDeviceID = oDiskDrive["PNPDeviceID"].ToString();
if(!szPNPDeviceID.StartsWith("USBSTOR"))
throw new Exception(szDriveName + " ist kein USB-Laufwerk.");
string[] aszToken = szPNPDeviceID.Split(new char[] { '\\', '&' });
szSerialNumberDevice = aszToken[aszToken.Length - 2];
}
}
if(null != szSerialNumberDevice)
{
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(@"root\CIMV2", "Select * from Win32_USBHub");
foreach(ManagementObject oResult in oSearcher.Get())
{
object oValue = oResult["DeviceID"];
if(oValue == null)
continue;
string szDeviceID = oValue.ToString();
string[] aszToken = szDeviceID.Split(new char[] { '\\' });
if(szSerialNumberDevice != aszToken[aszToken.Length - 1])
continue;
int nTemp = szDeviceID.IndexOf(@"VID_");
if(0 > nTemp)
continue;
nTemp += 4;
wVID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
nTemp += 4;
nTemp = szDeviceID.IndexOf(@"PID_", nTemp);
if(0 > nTemp)
continue;
nTemp += 4;
wPID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
bResult = true;
break;
}
}
return bResult;
}
public static bool GetDriveVidPid(string szDriveName, ref ushort wVID, ref ushort wPID)
{
bool bResult = false;
string szSerialNumberDevice = null;
ManagementObject oLogicalDisk = new ManagementObject("Win32_LogicalDisk.DeviceID='" + szDriveName.TrimEnd('\\') + "'");
foreach(ManagementObject oDiskPartition in oLogicalDisk.GetRelated("Win32_DiskPartition"))
{
foreach(ManagementObject oDiskDrive in oDiskPartition.GetRelated("Win32_DiskDrive"))
{
string szPNPDeviceID = oDiskDrive["PNPDeviceID"].ToString();
if(!szPNPDeviceID.StartsWith("USBSTOR"))
throw new Exception(szDriveName + " ist kein USB-Laufwerk.");
string[] aszToken = szPNPDeviceID.Split(new char[] { '\\', '&' });
szSerialNumberDevice = aszToken[aszToken.Length - 2];
}
}
if(null != szSerialNumberDevice)
{
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(@"root\CIMV2", "Select * from Win32_USBHub");
foreach(ManagementObject oResult in oSearcher.Get())
{
object oValue = oResult["DeviceID"];
if(oValue == null)
continue;
string szDeviceID = oValue.ToString();
string[] aszToken = szDeviceID.Split(new char[] { '\\' });
if(szSerialNumberDevice != aszToken[aszToken.Length - 1])
continue;
int nTemp = szDeviceID.IndexOf(@"VID_");
if(0 > nTemp)
continue;
nTemp += 4;
wVID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
nTemp += 4;
nTemp = szDeviceID.IndexOf(@"PID_", nTemp);
if(0 > nTemp)
continue;
nTemp += 4;
wPID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
bResult = true;
break;
}
}
return bResult;
}