Windows 7平台,C#
我使用以下语句列出所有驱动器:
DriveInfo[] drives = DriveInfo.GetDrives();
然后我可以使用DriveType查找所有可移动磁盘:
foreach (var drive in drives)
{
if(drive.DriveType == DriveType.Removable)
yield return drive;
}
现在我的问题是,SD卡磁盘和USB闪存盘共享相同的driveType:可移动,那我怎么才能找到USB闪存盘?
谢谢!
答案 0 :(得分:7)
您可以利用ManagementObjectSearcher
使用它来查询USB磁盘驱动器,然后获取相应的单位字母,并仅返回DriveInfo
中包含RootDirectory.Name
的{{1}}结果集。
使用LINQ查询表达式:
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = from drive in new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast<ManagementObject>()
from o in drive.GetRelated("Win32_DiskPartition").Cast<ManagementObject>()
from i in o.GetRelated("Win32_LogicalDisk").Cast<ManagementObject>()
select string.Format("{0}\\", i["Name"]);
return from drive in DriveInfo.GetDrives()
where drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name)
select drive;
}
使用LINQ扩展方法:
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get().Cast<ManagementObject>()
.SelectMany(drive => drive.GetRelated("Win32_DiskPartition").Cast<ManagementObject>())
.SelectMany(o => o.GetRelated("Win32_LogicalDisk").Cast<ManagementObject>())
.Select(i => Convert.ToString(i["Name"]) + "\\");
return DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name));
}
使用foreach:
static IEnumerable<string> GetUsbDrivesLetters()
{
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive WHERE InterfaceType='USB'").Get())
foreach (ManagementObject o in drive.GetRelated("Win32_DiskPartition"))
foreach (ManagementObject i in o.GetRelated("Win32_LogicalDisk"))
yield return string.Format("{0}\\", i["Name"]);
}
static IEnumerable<DriveInfo> GetUsbDevices()
{
IEnumerable<string> usbDrivesLetters = GetUsbDrivesLetters();
foreach (DriveInfo drive in DriveInfo.GetDrives())
if (drive.DriveType == DriveType.Removable && usbDrivesLetters.Contains(drive.RootDirectory.Name))
yield return drive;
}
要使用ManagementObject
,您需要添加对System.Management
我没有测试好,因为现在我没有任何SD卡,但我希望它有所帮助
答案 1 :(得分:1)
我必须在较旧的项目中检查USB设备,并解决此问题:
Win32.DEV_BROADCAST_DEVICEINTERFACE deviceInterface;
deviceInterface = (Win32.DEV_BROADCAST_DEVICEINTERFACE)
string name = new string(deviceInterface.dbcc_name);
Guid g = new Guid(deviceInterface.dbcc_classguid);
if (g.ToString() == "a5dcbf10-6530-11d2-901f-00c04fb951ed")
{*DO SOMETHING*}
我获取GUID并检查设备GUID是否为USB-GUID。