.netwindows-servicesremovable-storage

Detect Removable Media Ejection Request in Windows Service


I have a Windows service written in C# with the .NET 2.0 framework that uses the FileSystemWatcher to monitor certain directories for changes. Some of these directories may be on removable media, such as a USB drive. When a new drive is plugged into the system, I get notification through a WMI query and can set up a new FileSystemWatcher. All that works well.

The difficulty is that I want the user to be able to eject the drive using the Windows "Safely Remove Hardware" app, but Windows reports that the drive is busy because I'm monitoring it via FileSystemWatcher, and tells the user the drive cannot be removed.

My question, then, is how can my Windows Service know when the user requests ejection, so that I can remove my file system monitor and allow the request to succeed?


Solution

  • You need to register to receive the device removal query broadcast event (DBT_DEVICEQUERYREMOVE), via the RegisterDeviceNotification Windows API, as explained here.

    As far as I know there is no .NET Framework class which wraps this functionality, so you'll need to do it long-hand using p/Invoke.