【问题标题】:How do I get newly inserted USB drive letter in c#?如何在 c# 中获取新插入的 USB 驱动器号?
【发布时间】:2016-04-25 06:20:19
【问题描述】:

我写了一个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 drive = DriveInfo.GetDrives() .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
  • 这将选择系统中存在的所有可移动驱动器
  • 看看这个 satckoverflow 链接它有太多信息stackoverflow.com/questions/6003822/…
  • 我从codeproject.com/Messages/2126647/Re-Csharp-USB-Detection.aspx 找到了一个解决方案,他们使用TargetInstance ISA 'Win32_LogicalDisk' 而不是TargetInstance ISA 'Win32_DiskDriveToDiskPartition',它对我有用。
  • 我仍然不知道它为什么会起作用,因为我所有的 USB 闪存驱动器都是主分区。谁能解释一下?

标签: c# managementeventwatcher


【解决方案1】:

您可能过于努力地重新创建一个预先存在的灵魂。这是一个由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(例如驱动器号)。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多