Detect Removable Media Ejection Request in Windows Service

女生的网名这么多〃 提交于 2019-12-11 00:46:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4783481/detect-removable-media-ejection-request-in-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!