Looking for C# code for detecting removable drive (usb flash)

蓝咒 提交于 2019-11-27 15:43:33
Powerlord

There's a class called DriveDetector over at Codeproject that sounds like it does what you want.

Look at WM_DEVICECHANGE. This message should be sent when a drive is inserted.

Matt Warren

I know this is not exactly what you asked for, but if you want to check what devices are available at any moment in time, there's another way. You can use the WMI classes in the System.Management namespace, I've used this method and it works well.

If you take a look at this answer, it shows how to enumerate all the drives on the system. You can then take a look at the drive type to determine whether or not it's a USB stick.

I wrote a powershell module that uses a System.Management.ManagementEventWatcher and the WMI class Win32_VolumeChangedEvent to surface new events that you may register for within powershell covering device removal, addition etc. You should be able to figure out the relevant plumbing from this blog post of mine:

http://www.nivot.org/nivot2/post/2008/08/16/AutoMountunmountNewPSDrivesForRemovableDrivesAndNetworkSharesInPowerShellV2.aspx

You should be able to wire up an event for new drives in less than ten lines of C# using the methods I use in the above script.

Hope this helps.

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