如何在服务项目中获得一个插入的USB驱动器号?

Dan*_*225 2 .net c# usb service

我总是使用覆盖WndProc(ref Message m)的方法来获取插入/删除驱动器的事件,并创建我自己的eventarg以返回驱动器号.这完美地工作但现在我正在忙于开发服务项目,显然不能使用上述方法.

我现在正在使用WMI:

    //insert
    WqlEventQuery creationQuery = new WqlEventQuery();
    creationQuery.EventClassName = "__InstanceCreationEvent";
    creationQuery.WithinInterval = new TimeSpan(0, 0, 2);
    creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
    ManagementEventWatcher creationWatcher = new ManagementEventWatcher(creationQuery);

    creationWatcher.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
    creationWatcher.Start();
Run Code Online (Sandbox Code Playgroud)

插入USB闪存时,这可以正确地触发事件.现在我需要帮助的是如何从事件中获取驱动器号(例如E :)?

这是我到目前为止在我的活动中玩过的:

    internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
    {
        EventLog.WriteEntry("USB PLUGGED IN!");
        ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
        foreach (var property in instance.Properties)
        {
            EventLog.WriteEntry(property.Name + " = " + property.Value);

        }
    }
Run Code Online (Sandbox Code Playgroud)

我无法从"属性"中获取驱动器号.有没有办法得到驱动器号?或者我是否需要从完全不同的角度来看问题?

Dan*_*225 7

经过很多挫折,我得到了它的工作!

解决方案是,而不是使用:

creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
Run Code Online (Sandbox Code Playgroud)

将其更改为:

creationQuery.Condition = @"TargetInstance ISA 'Win32_LogicalDisk'";
Run Code Online (Sandbox Code Playgroud)

现在在事件函数中,EventArrivedEventArgs e将包含驱动器号的属性.

    internal 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

property.Value包含当property.Name ="Name"时的驱动器号