5

我构建了一个小脚本来检查具有给定名称的 USB 记忆棒是否已插入计算机,但现在我想围绕此脚本构建一个服务来观察记忆棒是否已插入。起初,我尝试使用 filewatcher 执行此操作并在 Stick 上创建一个文件,但如果从 pc 中移除棒并重新插入 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");
        }
    }
}
4

1 回答 1

9

您可以使用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
        }
    }

连接 USB 棒时,我将收到 7 个附加(分别为分离)事件。根据需要自定义附加/分离方法。阻塞部分留给读者,根据他的需要,你根本不需要阻塞的 Windows 服务。

于 2013-08-06T16:47:14.333 回答