簡體   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