简体   繁体   中英

Getting the Drive letter of USB drive inserted

I have detected the insertion of USB drive in my WPF application by following suggestions in given link How do I detect when a removable disk is inserted using C#?

but I am unable to figure out the Drive letter of the detected USB drive; my Code is given below

    static ManagementEventWatcher w = null;
    static void AddInsertUSBHandler()
    {

        WqlEventQuery q;
        ManagementScope scope = new ManagementScope("root\\CIMV2");
        scope.Options.EnablePrivileges = true;

        try {

            q = new WqlEventQuery();
            q.EventClassName = "__InstanceCreationEvent";
            q.WithinInterval = new TimeSpan(0, 0, 3);
            q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
            w = new ManagementEventWatcher(scope, q);
            w.EventArrived += USBInserted;

            w.Start();
        }
        catch (Exception e) {

            Console.WriteLine(e.Message);
            if (w != null)
            {
                w.Stop();

            }
        }

    }

    static void USBInserted(object sender, EventArgs e)
    {

        Console.WriteLine("A USB device inserted");

    } 

Kindly guide me if possible.

Hope this helps, its code based on Neeraj Dubbey's answer.

We run code in a continuous multithreaded loop that keeps checking for a change in connected USB devices. Because we keep track of previously connected devices we can compare it against a new list of devices. We can also determine if a device is removed using the same method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Usb_Test
{
    class Program
    {
        private static List<USBDeviceInfo> previousDecices = new List<USBDeviceInfo>();

        static void Main(string[] args)
        {
            Thread thread = new Thread(DeviceDetection);
            thread.Start();

            Console.Read();
        }

        static void DeviceDetection()
        {
            while (true)
            {
                List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

                ManagementObjectCollection collection;
                using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
                    collection = searcher.Get();

                foreach (var device in collection)
                {
                    devices.Add(new USBDeviceInfo(
                    (string)device.GetPropertyValue("DeviceID")
                    ));
                }

                if (previousDecices == null || !previousDecices.Any()) // So we don't detect already plugged in devices the first time.
                    previousDecices = devices;

                var insertionDevices = devices.Where(d => !previousDecices.Any(d2 => d2.DeviceID == d.DeviceID));
                if (insertionDevices != null && insertionDevices.Any())
                {
                    foreach(var value in insertionDevices)
                    {
                        Console.WriteLine("Inserted: " + value.DeviceID); // Add your own event for the insertion of devices.
                    }
                }    

                var removedDevices = previousDecices.Where(d => !devices.Any(d2 => d2.DeviceID == d.DeviceID));
                if (removedDevices != null && removedDevices.Any())
                {
                    foreach (var value in removedDevices)
                    {
                        Console.WriteLine("Removed: " + value.DeviceID); // Add your own event for the removal of devices.
                    }
                }

                previousDecices = devices;
                collection.Dispose();
            }
        }
    }

    class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID)
        {
            this.DeviceID = deviceID;
        }
        public string DeviceID { get; private set; }

    }
}

However this is not a great solution, you're a lot better off listening for WM_DEVICECHANGE.

Windows will send WM_DEVICECHANGE message to all applications whenever some hardware change occurs, including when a flash drive (or other removable device) is inserted or removed. The WParam parameter of this message contains code which specifies exactly what event occurred. For our purpose only the following events are interesting:

DBT_DEVICEARRIVAL - sent after a device or piece of media has been inserted. Your program will receive this message when the device is ready for use, at about the time when Explorer displays the dialog which lets you choose what to do with the inserted media.

DBT_DEVICEQUERYREMOVE - sent when the system requests permission to remove a device or piece of media. Any application can deny this request and cancel the removal. This is the important event if you need to perform some action on the flash drive before it is removed, eg encrypt some files on it. Your program can deny this request which will cause Windows to display the well-known message saying that the device cannot be removed now.

DBT_DEVICEREMOVECOMPLETE - sent after a device has been removed. When your program receives this event, the device is no longer available — at the time when Windows display its "device has been removed" bubble to the user.

Here are some links that each detail an answer on how to do this in C#:

http://www.codeproject.com/Articles/18062/Detecting-USB-Drive-Removal-in-aC-Program http://www.codeproject.com/Articles/60579/A-USB-Library-to-Detect-USB-Devices

Both solution should work, and you can always adapt them to fit your needs.

Hey try this console based code afetr adding the reference of System.Management in project

namespace ConsoleApplication1
{
 using System;
 using System.Collections.Generic;
 using System.Management; // need to add System.Management to your project references.

class Program
{
static void Main(string[] args)
{
    var usbDevices = GetUSBDevices();

    foreach (var usbDevice in usbDevices)
    {
        Console.WriteLine("Device ID: {0}", usbDevice.DeviceID);

    }

    Console.Read();
}

static List<USBDeviceInfo> GetUSBDevices()
{
    List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

    ManagementObjectCollection collection;
    using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
        collection = searcher.Get();

    foreach (var device in collection)
    {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID")
        ));
    }

    collection.Dispose();
    return devices;
}
}

class USBDeviceInfo
{
public USBDeviceInfo(string deviceID)
{
    this.DeviceID = deviceID;
}
public string DeviceID { get; private set; }

}

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