简体   繁体   中英

How to get an insterted USB drive letter in a service project?

I've always used the method of overriding WndProc(ref Message m) to get events for drive inserted/removed and created my own eventarg to return the drive letter. This worked perfectly but now I'm busy developing a service project and obviously cannot use the above-mentioned method.

I'm using now 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();

This correctly lets the event fire when a USB flash is plugged in. Now what I need help with is how to get the drive letter (eg E:) from the event?

Here is what I have played around in my event so far:

    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);

        }
    }

I can't get the drive letter from "Properties". Is there a way to get the drive letter? Or do I need to look at the problem from a completely different angle?

After a lot of frustration, I got it working!

the solution is, instead of using:

creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";

Change it to:

creationQuery.Condition = @"TargetInstance ISA 'Win32_LogicalDisk'";

Now in the event function, the properties from the EventArrivedEventArgs e will include drive letter.

    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);
        }
    }

property.Value contains the Drive letter when property.Name = "Name"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM