简体   繁体   中英

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

我正在寻找一个C#代码片段给我一个通知,说明在Windows Vista(或win7)中将USB驱动器插入我的电脑的时间

Codeproject上有一个名为DriveDetector的类,听起来像是你想要的。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM