如何创建一个监视进程来检测可移动USB设备

本文关键字:检测 进程 可移动 设备 USB 监视 何创建 创建 一个 | 更新日期: 2023-09-27 18:26:00

我构建了一个小脚本,用于检查具有给定名称的U盘是否已插入计算机,但现在我想围绕这个脚本构建一个服务,以查看U盘是否插入。起初,我试图用filewatcher来做这件事,并在Stick上创建一个文件,但如果从电脑上删除Stick并重新插入filewatcher,我就无法实现。下面的脚本会检查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");
        }
    }
}

如何创建一个监视进程来检测可移动USB设备

您可以使用ManagementEventWatcher挂接(USB)事件。

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

连接U盘时,我将收到7个连接(分别为分离)事件。根据需要自定义附加/拆离方法。阻止部分留给读者,这取决于他的需求,使用Windows服务,你根本不需要阻止。