如何创建一个watcherprocess来检测可移动的USB设备?

koc*_*ren 4 .net c# winapi

我构建了一个小脚本,用于检查具有给定名称的USB Stick是否已插入计算机,但现在我想围绕此脚本构建一个服务,以观察Stick是否插入.起初我尝试用filewatcher执行此操作并在Stick上创建一个文件,但是如果从PC上取下棒并重新插入filewatcher dosent意识到它.以下脚本检查Stick是否插入,但我需要一个脚本来循环此DriveInfo.GetDrive函数.我不知道最好的方法是在这个函数周围建立一个10秒的定时器循环,或者.NET Framework中是否有可移动设备的观察者类.脚本来了:

public static void Main()
{
    Run();
}

public static void Run()
{                     
    var drives = DriveInfo.GetDrives()
        .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
    if (drives.Count() > 0)
    {
        foreach (var drive in drives)
        {
           if (drive.VolumeLabel == "TESTLABEL") Console.WriteLine("USB Stick is plugged in");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mbx*_*mbx 9

您可以使用连接到(USB)事件ManagementEventWatcher.

LinqPad的工作示例解释了这个使用以下内容的简洁答案Win32_DeviceChangeEvent:

// using System.Management;
// reference System.Management.dll
void Main()
{    
    using(var control = new USBControl()){
        Console.ReadLine();//block - depends on usage in a Windows (NT) Service, WinForms/Console/Xaml-App, library
    }
}

class USBControl : IDisposable
    {
        // used for monitoring plugging and unplugging of USB devices.
        private ManagementEventWatcher watcherAttach;
        private ManagementEventWatcher watcherDetach;

        public USBControl()
        {
            // Add USB plugged event watching
            watcherAttach = new ManagementEventWatcher();
            watcherAttach.EventArrived += Attaching;
            watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
            watcherAttach.Start();

            // Add USB unplugged event watching
            watcherDetach = new ManagementEventWatcher();
            watcherDetach.EventArrived += Detaching;
            watcherDetach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
            watcherDetach.Start();
        }

        public void Dispose()
        {
            watcherAttach.Stop();
            watcherDetach.Stop();
            //you may want to yield or Thread.Sleep
            watcherAttach.Dispose();
            watcherDetach.Dispose();
            //you may want to yield or Thread.Sleep
        }

        void Attaching(object sender, EventArrivedEventArgs e)
        {
            if(sender!=watcherAttach)return;
            e.Dump("Attaching");
        }

        void Detaching(object sender, EventArrivedEventArgs e)
        {
            if(sender!=watcherDetach)return;
            e.Dump("Detaching");
        }

        ~USBControl()
        {
            this.Dispose();// for ease of readability I left out the complete Dispose pattern
        }
    }
Run Code Online (Sandbox Code Playgroud)

连接USB-Stick时,我将收到7个附加(分配)事件.根据需要自定义附加/分离方法.阻止部分留给读者,根据他的需要,使用您根本不需要阻止的Windows服务.