2

I need to connect and disconnect USB programmatically. That is, I have inserted the USB device. I need to transfer the file using C#, .NET application. The application will watch the particular folder and transfer the file from that folder to a USB drive. I need to disconnect the USB device after the file is transfered and connect the USB when needed - without unplug and replug.

What would be some code to do it or is there any DLL file available?

Main thing: NOTE, NOTE: Without unplugging and replugging the USB device.

1

2 Answers 2

3

If your goal is to make a certain disk volume unavailable while you're not using it, a more sensible approach might be to use the volume management APIs, e.g. by using the IOCTL_VOLUME_OFFLINE control code. (I'm assuming that you know which drive letter belongs to your USB disk.)

Alternatively, you can disable and enable the volume device programmatically with the CfgMgr / SetupAPI -- the same as right-clicking the volume in Device Manager and choosing Disable would do. (For information about using SetupAPI, please review the DevCon sample code provided with the Windows WDK, and see MSDN for functions such as SetupDiChangeState.)

The latter option might require a privileged user account.

1
  • 1
    Do you have a reference for the CfgMgr API? If you do, you may edit it into your answer. Feb 13, 2015 at 16:04
0

I'm not exactly sure, but it can be done. In Linux, I've experienced certain situations where power is disconnected to a device programmatically. The kernel usually does this if the connected USB device is exhibiting too many errors. So, it should be possible to do this even in Windows. You may need to write your own external DLL to do it though.

2
  • On common USB host controllers, there's no way (in hardware) to disconnect power from a USB port programatically, so it's unlikely Windows can do that.
    – Ilya
    May 27, 2011 at 2:05
  • Ilya, next time please use search first, before commenting like that and voting down other (correct) answers. See here for more info: stackoverflow.com/questions/4702216/…
    – Mladen B.
    Nov 28, 2013 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.