Eject Memory card from Card Reader C#

2019-01-27 05:08发布

I have a custom developed USB card reader. I am using the following code to interact and iterrate over the device:

http://www.codeproject.com/KB/system/usbeject.aspx

The code above provides an 'eject' method using the following line:

Native.CM_Request_Device_Eject_NoUi(device.InstanceHandle, IntPtr.Zero, null, 0, 0);

However this 'eject' method unmounts the entire drive instead of simply ejecting the media card.

Why this is a problem is because I want to 'eject' the media card, then put in a different one. However when the whole reader is ejected i have to unplug/replug the device for it to show back up.

In windows explorer when I right click 'eject' it operates as I am imagining, where it safely removes the memory card but not the card reader.

How can I go about impelmenting this different type of eject in c#?

Thanks, Stephanie

标签: c# usb eject
2条回答
爷的心禁止访问
2楼-- · 2019-01-27 06:09

I'v the same task. :)

You need use ejecting removable media. See c++ sample here: How To Ejecting Removable Media

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-27 06:10

I came here accidentally while doing a search on "CM_Request_Device_Eject_NoUi", and saw that it was similar to a solution I'd recently done by pulling together similar pieces of a solution. Forgive the late answers.

Here's what worked for me (this also addresses some issues I've seen on other SO questions regarding AutoEjectVolume from the Microsoft sample not "doing everything" that the system does when you Safely Remove Hardware using the OS):

  1. Start with the steps outlined in How to Eject Removable Media in Windows.
  2. Replace the call to AutoEjectVolume with code that is, in effect, the body of the RemoveDrive method from How to Prepare a USB Drive for Safe Removal. Note that this later work relies heavily on two other CodeProject articles — including the one you referenced in your question — ported to C#.

In 2, I say "in effect" because — in practice — you use the same hVolume in both solutions, and it makes more sense to do all the checks in the CodeProject RemoveDrive method before calling LockVolume, DismountVolume, or PrepareRemovalOfVolume in the Microsoft solution, and then call CM_Request_Device_Eject_NoUi as shown in the CodeProject solution.

A short pseudo-code summary:

  • Open the volume with CreateFile (CodeProject)
  • Obtain drive's device instance handle and drive's parent's device instance handle (CodeProject)
  • Exit before calling — in particular — DismountVolume, if any of the steps above fail (CodeProject)
  • Call LockVolume, DismountVolume, and PrepareRemovalOfVolume using the hVolume returned from CreateFile (Microsoft)
  • You can close the hVolume at any time after this
  • Call CM_Request_Device_Eject_NoUi on the drive's parent's device
    instance handle (CodeProject)
查看更多
登录 后发表回答