【发布时间】:2013-06-26 15:10:56
【问题描述】:
所以我想我会在此处包含最终答案,这样您就不必理解这篇文章了。非常感谢 Simon Mourier 花时间解决这个问题。
我的工作代码
try
{
//Get a list of available devices attached to the USB hub
List<string> disks = new List<string>();
var usbDevices = GetUSBDevices();
//Enumerate the USB devices to see if any have specific VID/PID
foreach (var usbDevice in usbDevices)
{
if (usbDevice.DeviceID.Contains(USB_PID) && usbDevice.DeviceID.Contains(USB_VID))
{
foreach (string name in usbDevice.GetDiskNames())
{
//Open dialog to show file names
textbox1.Text = name.ToString();
}
}
}
所以只需使用我原始问题中的GetUSBDevices,然后包括 Simon Mourier 的回答中显示的两个类,这应该很好!
原始问题
我知道以前有人问过这个问题(请参阅here),但他们都没有确定的答案,我已经尝试了所有建议的答案。不幸的是,这些线程早已死去,我希望有人能在这里给出更好的答案。
到目前为止,我有两个“起点”,我将在下面展示每个起点。
选项 1:(获取 VID/PID 但不获取驱动器号)
我有一个通过应用程序连接到的嵌入式设备。我有成功扫描任何 USB 设备并检查 VID/PID 的代码。我成功检测到我的设备,但我不知道如何获取驱动器号。有人可以帮我吗?我觉得我可以在 class 中添加另一行,但是当我通过 Device Manager 时,我找不到任何描述驱动器号的属性。
谢谢!
我将在下面包含我的代码。
private void tsDownload_Click(object sender, EventArgs e)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
if (usbDevice.DeviceID.Contains(USB_PID) && usbDevice.DeviceID.Contains(USB_VID))
{
//Find drive letter here
}
}
}
这些函数在哪里:
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
班级是:
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
}
选项 2:(获取驱动器号,但不获取 VID/PID)
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
{
foreach(ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
textBox1.Text = disk["Name"].ToString();
}
}
}
我猜 VID/PID 位于 disk 对象属性之一中,但我找不到哪个。
【问题讨论】:
-
+1 用于研究工作。我希望你能得到你正在寻找的答案。我也很好奇。
-
我认为这种混淆/困难来自于并非每个设备都有驱动器号的事实,即使这样,一个设备也可以有很多驱动器号。只是我的新手理解......
-
我已经连接了两个 USB 智能卡读卡器,但是当我运行 OPTION 2 示例时,我没有在“ManagementObjectSearcher”中连接任何 USB。