在C#中如何获取新插入的USB驱动器盘符?

4

我写了一个C#程序来查找新插入的USB驱动器及其驱动器号。 现在当我运行此程序时,我可以获得插入事件,但无法获取驱动器号。 有人能给我建议吗?

代码

static void Main(string[] args)
{
    ManagementEventWatcher mwe_creation; //Object creation for 'ManagementEventWatcher' class is used to listen the temporary system event notofications based on specific query. 
    WqlEventQuery q_creation = new WqlEventQuery(); //Represents WMI(Windows Management Instrumentation) event query in WQL format for more information goto www.en.wikipedia.org/wiki/WQL
    q_creation.EventClassName = "__InstanceCreationEvent";// Sets the eventclass to the query
    q_creation.WithinInterval = new TimeSpan(0, 0, 2);    // Setting up the time interval for the event check(here, it is 2 Seconds)
    q_creation.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'"; //Sets which kind of event  to be notified
    mwe_creation = new ManagementEventWatcher(q_creation); //Initializing new instance
    mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);//Calling up 'USBEventArrived_Creation' method when the usb storage plug-in event occured
    mwe_creation.Start(); // Starting to listen to the system events based on the given query
    while (true) ;

}
static void USBEventArrived_Creation(object sender, EventArrivedEventArgs e){

    Console.WriteLine("USB PLUGGED IN!");
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {

        if (property.Name == "Name")
            Console.WriteLine(property.Name + " = " + property.Value);
    }

}

你有尝试过这个吗 var drives = DriveInfo.GetDrives() .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable); - rashfmnb
这将选择系统中存在的所有可移动驱动器。 - Hybrid Developer
请查看这个Stack Overflow链接,它包含了很多信息:https://dev59.com/3W025IYBdhLWcg3wcli- - rashfmnb
我从http://www.codeproject.com/Messages/2126647/Re-Csharp-USB-Detection.aspx找到了一个解决方案,他们使用`TargetInstance ISA 'Win32_LogicalDisk'而不是TargetInstance ISA 'Win32_DiskDriveToDiskPartition'`,这对我有效。 - Hybrid Developer
我仍然不知道为什么它能够工作,因为我所有的USB闪存驱动器都是主分区。有人可以解释一下吗? - Hybrid Developer
Win32_DiskDriveToDiskPartition没有任何事件,所以这是无法工作的。请谷歌“Win32_VolumeChangeEvent”以获取更多信息。这篇博客文章看起来不错。 - Hans Passant
1个回答

0

你可能正在努力重新创建一个已经存在的解决方案。这里有一个由Stephen Mcohn制作的公共许可项目,它提供了你需要的界面,并且似乎有很好的文档记录:

http://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives

以下是他如何仅筛选USB驱动器的方法

new ManagementObjectSearcher(
        "select DeviceID, Model from Win32_DiskDrive " +
         "where InterfaceType='USB'").Get())

以下是如何恢复特定驱动器字母的方法

使用Associators获取Win32_LogicalDisk来获取特定驱动器字母的设备ID(例如驱动器字母)。

如果您不想导入Stephen的整个模块,Microsoft提供了一个VB代码示例,您可以进行移植:

ComputerName = "."
Set wmiServices  = GetObject ( _
    "winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
' Get physical disk drive
Set wmiDiskDrives =  wmiServices.ExecQuery ( "SELECT Caption, DeviceID FROM Win32_DiskDrive")

For Each wmiDiskDrive In wmiDiskDrives
    WScript.Echo "Disk drive Caption: " & wmiDiskDrive.Caption & VbNewLine & "DeviceID: " & " (" & wmiDiskDrive.DeviceID & ")"

    'Use the disk drive device id to
    ' find associated partition
    query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _
        & wmiDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition"    
    Set wmiDiskPartitions = wmiServices.ExecQuery(query)

    For Each wmiDiskPartition In wmiDiskPartitions
        'Use partition device id to find logical disk
        Set wmiLogicalDisks = wmiServices.ExecQuery _
            ("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _
             & wmiDiskPartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition") 

        For Each wmiLogicalDisk In wmiLogicalDisks
            WScript.Echo "Drive letter associated" _
                & " with disk drive = " _ 
                & wmiDiskDrive.Caption _
                & wmiDiskDrive.DeviceID _
                & VbNewLine & " Partition = " _
                & wmiDiskPartition.DeviceID _
                & VbNewLine & " is " _
                & wmiLogicalDisk.DeviceID
        Next      
    Next
Next

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接