Detecting USB drive insertion and removal using windows service and c#

Kb. picture Kb. · Mar 6, 2009 · Viewed 84.2k times · Source

Looking into possibility of making an USB distributed application
that will autostart on insertion of an USB stick and shutdown when removing the stick

Will use .Net and C#.
Looking for suggestion how to approach this using C#?


Update: Two possible solutions implementing this as a service.
- override WndProc
or
- using WMI query with ManagementEventWatcher

Answer

VitalyB picture VitalyB · Jun 7, 2010

You can use WMI, it is easy and it works a lot better than WndProc solution with services.

Here is a simple example:

using System.Management;

ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
watcher.WaitForNextEvent();