USB detection
Windows service
C# programming
Hardware monitoring
Software development

Detecting USB drive insertion and removal using windows service and c

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Detecting USB insertion and removal from a Windows service is different from doing it in a desktop application. A service runs in session 0, so UI-oriented message loops such as WM_DEVICECHANGE are usually the wrong integration point.

For service code, WMI is often the simplest approach. A ManagementEventWatcher can subscribe to Win32_VolumeChangeEvent and react when removable storage appears or disappears without depending on a visible window.

Use a Service-Friendly Detection Mechanism

Desktop examples often rely on window messages. In a background service, WMI tends to be easier to host and reason about.

The two event types you usually care about are:

  • '2 for insertion'
  • '3 for removal'

That gives you a clean starting point for drive-letter based USB storage events.

Create Watchers in the Service Lifecycle

The service should create its watchers in OnStart and dispose them in OnStop:

csharp
1using System;
2using System.Management;
3using System.ServiceProcess;
4
5public class UsbMonitorService : ServiceBase
6{
7    private ManagementEventWatcher _insertWatcher;
8    private ManagementEventWatcher _removeWatcher;
9
10    public UsbMonitorService()
11    {
12        ServiceName = "UsbMonitorService";
13    }
14
15    protected override void OnStart(string[] args)
16    {
17        _insertWatcher = CreateWatcher(
18            "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2",
19            "inserted"
20        );
21
22        _removeWatcher = CreateWatcher(
23            "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3",
24            "removed"
25        );
26    }
27
28    protected override void OnStop()
29    {
30        StopWatcher(_insertWatcher);
31        StopWatcher(_removeWatcher);
32    }
33
34    private ManagementEventWatcher CreateWatcher(string query, string verb)
35    {
36        var watcher = new ManagementEventWatcher(query);
37        watcher.EventArrived += (_, e) =>
38        {
39            var driveName = Convert.ToString(e.NewEvent["DriveName"]);
40            Log($"{driveName} {verb}");
41        };
42        watcher.Start();
43        return watcher;
44    }
45
46    private void StopWatcher(ManagementEventWatcher watcher)
47    {
48        if (watcher == null) return;
49        watcher.Stop();
50        watcher.Dispose();
51    }
52
53    private void Log(string message)
54    {
55        EventLog.WriteEntry(ServiceName, message);
56    }
57}

This is a good baseline because it matches the service lifecycle cleanly and does not depend on any interactive session state.

Filter for Removable Media

Not every volume event is a USB stick. If your service should react only to removable media, verify the drive type before doing real work.

csharp
1using System.IO;
2
3private bool IsRemovable(string driveName)
4{
5    if (string.IsNullOrWhiteSpace(driveName))
6    {
7        return false;
8    }
9
10    var drive = new DriveInfo(driveName);
11    return drive.DriveType == DriveType.Removable;
12}

Use that check inside the event handler before starting downstream logic such as scanning, copying, or indexing files.

Keep the Callback Lightweight

The WMI callback should not do heavy work directly. Treat it as a signal, then queue background processing:

csharp
1private void HandleDriveInserted(string driveName)
2{
3    if (!IsRemovable(driveName))
4    {
5        return;
6    }
7
8    Log($"Queueing processing for {driveName}");
9    // Hand off to a worker queue here.
10}

This matters because long-running event handlers can make service behavior unpredictable when several devices are connected or removed in quick succession.

Operational Concerns

A Windows service should always log enough detail to diagnose startup problems, permission issues, and watcher failures. Event Log is a good default because it is available even when there is no UI.

Also decide what you really mean by detection. Some systems care about mounted volumes with drive letters. Others care about any USB mass storage device, even before it becomes usable as a filesystem. Those are related but different monitoring problems.

Common Pitfalls

  • Using WM_DEVICECHANGE logic that depends on a window handle inside a service.
  • Doing long-running file operations directly in the WMI event callback.
  • Assuming every volume event is removable USB media.
  • Forgetting to stop and dispose watchers when the service stops.
  • Logging too little to diagnose service startup and hardware-event issues.

Summary

  • Windows services should usually detect USB storage through WMI rather than UI window messages.
  • 'Win32_VolumeChangeEvent is a practical event source for insert and remove detection.'
  • Filter for removable media if the service should ignore non-USB volume changes.
  • Keep event handlers small and hand off real work to background processing.
  • Add proper logging and watcher cleanup so the service behaves predictably.

Course illustration
Course illustration

All Rights Reserved.