繁体   English   中英

插入USB驱动器的驱动器号

[英]Getting the Drive letter of USB drive inserted

通过遵循给定链接中的建议,我已检测到WPF应用程序中已插入USB驱动器。 如何检测何时使用C#插入了可移动磁盘?

但我无法找出检测到的USB驱动器的驱动器号; 我的代码如下

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

    } 

如果可以的话,请指导我。

希望这对您有所帮助,其代码基于Neeraj Dubbey的回答。

我们在一个连续的多线程循环中运行代码,该循环不断检查所连接的USB设备的更改。 由于我们跟踪以前连接的设备,因此可以将其与新设备​​列表进行比较。 我们还可以确定是否使用相同的方法删除设备。

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

    }
}

但这不是一个很好的解决方案,您最好听WM_DEVICECHANGE。

每当发生某些硬件变化时,包括插入或卸下闪存驱动器(或其他可移动设备)时,Windows都会向所有应用程序发送WM_DEVICECHANGE消息。 此消息的WParam参数包含精确指定发生了什么事件的代码。 就我们而言,仅以下事件是有趣的:

DBT_DEVICEARRIVAL-插入设备或媒体后发送。 当设备准备好使用时,大约在资源管理器显示对话框时,您的程序将收到此消息,该对话框使您可以选择对插入的媒体进行处理。

DBT_DEVICEQUERYREMOVE-在系统请求删除设备或媒体的权限时发送。 任何应用程序都可以拒绝此请求并取消删除。 如果您需要在闪存驱动器上执行某些操作之前将其删除,例如对其中的某些文件进行加密,则这是重要事件。 您的程序可以拒绝此请求,这将导致Windows显示众所周知的消息,指出无法立即删除该设备。

DBT_DEVICEREMOVECOMPLETE-删除设备后发送。 当您的程序收到此事件时,该设备将不再可用-Windows向用户显示其“设备已被删除”气泡时。

以下是一些链接,每个链接都详细说明了如何在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设备

两种解决方案都应该起作用,并且您始终可以对其进行调整以满足您的需求。

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