Building a Responsive C# Windows Service for USB Drive Detection
Many distributed applications need to react to the insertion and removal of USB drives. This article demonstrates how to create a C# Windows service that achieves this reliably. We'll leverage the Windows Management Instrumentation (WMI) API, offering superior reliability and compatibility compared to methods like WndProc, which are unsuitable for services.
The following code snippet provides a fundamental WMI-based implementation:
<code class="language-csharp">using System.Management; // Create a ManagementEventWatcher to monitor for volume change events. ManagementEventWatcher watcher = new ManagementEventWatcher(); // Define a WQL query to filter for volume insertion events (EventType = 2). WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); // Attach an event handler to process detected events. watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); // Assign the query to the watcher. watcher.Query = query; // Start monitoring. watcher.Start(); // Wait for the next event. Consider using a more robust loop for continuous monitoring. watcher.WaitForNextEvent();</code>
This code establishes a watcher that listens for Win32_VolumeChangeEvent
events where EventType
is 2 (indicating media insertion).
Event Handling and Response
The watcher_EventArrived
event handler (not shown) will contain the logic to respond to the drive insertion. This might involve starting a distributed application or performing other necessary actions.
Robustness and Error Handling
Implementing comprehensive error handling and exception management is crucial for ensuring the service's continued operation, even when encountering unexpected errors. This should be incorporated into the watcher_EventArrived
method.
Extending Functionality
This basic example can be customized for various scenarios. You can modify the event handling, create multiple watchers for different media types, and add event handling for drive removal (EventType = 3).
WMI empowers Windows services to dynamically react to USB drive events, resulting in more responsive and adaptable distributed applications.
The above is the detailed content of How Can a C# Windows Service Detect USB Drive Insertion and Removal?. For more information, please follow other related articles on the PHP Chinese website!