简体   繁体   English

插入USB驱动器的驱动器号

[英]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#? 通过遵循给定链接中的建议,我已检测到WPF应用程序中已插入USB驱动器。 如何检测何时使用C#插入了可移动磁盘?

but I am unable to figure out the Drive letter of the detected USB drive; 但我无法找出检测到的USB驱动器的驱动器号; 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. 希望这对您有所帮助,其代码基于Neeraj Dubbey的回答。

We run code in a continuous multithreaded loop that keeps checking for a change in connected USB devices. 我们在一个连续的多线程循环中运行代码,该循环不断检查所连接的USB设备的更改。 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. 但这不是一个很好的解决方案,您最好听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. 每当发生某些硬件变化时,包括插入或卸下闪存驱动器(或其他可移动设备)时,Windows都会向所有应用程序发送WM_DEVICECHANGE消息。 The WParam parameter of this message contains code which specifies exactly what event occurred. 此消息的WParam参数包含精确指定发生了什么事件的代码。 For our purpose only the following events are interesting: 就我们而言,仅以下事件是有趣的:

DBT_DEVICEARRIVAL - sent after a device or piece of media has been inserted. DBT_DEVICEARRIVAL-插入设备或媒体后发送。 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. DBT_DEVICEQUERYREMOVE-在系统请求删除设备或媒体的权限时发送。 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. 您的程序可以拒绝此请求,这将导致Windows显示众所周知的消息,指出无法立即删除该设备。

DBT_DEVICEREMOVECOMPLETE - sent after a device has been removed. DBT_DEVICEREMOVECOMPLETE-删除设备后发送。 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. 当您的程序收到此事件时,该设备将不再可用-Windows向用户显示其“设备已被删除”气泡时。

Here are some links that each detail an answer on how to do this in C#: 以下是一些链接,每个链接都详细说明了如何在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 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设备

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 嘿,请尝试在此基于控制台的代码之后,在项目中添加System.Management的引用。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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