0

I am using C# and I would like to disconnect a connected device that is connected on COM4. I have tried to use SerialPort but it gives access denied and its not reliable even if I add delay between open and close port.

moe1792
  • 29
  • 6
  • I don't think you can. Dismount is designed only for drives, and dismounts the volume, other USB devices may or may not have their own proprietary shutdown procedure, but the best you are going to get is to disable the device programmatically, similar to Device Manager – Charlieface Feb 09 '21 at 21:07
  • Are you trying to have a software version of pulling the USB device out of the port? Or are you trying to close open handles to the device, leaving the device recognized so that your program can connect? "access denied" on a serial port usually means that some other program is using the device – Ben Voigt Feb 09 '21 at 21:49
  • Isn't it an [XY problem](https://meta.stackexchange.com/a/66378)? It's a good idea to check which process is using the serial port when something goes wrong before you think about what to do. [Determine Which Process is Reserving Serial Port](https://knowledge.ni.com/KnowledgeArticleDetails?id=kA03q000000YGw9CAG&l=en-US), [How do I determine which process is using a serial port?](https://stackoverflow.com/q/42197/9014308) If it is your own program, you may need to take some measures other than adjusting the Close/ReOpen interval. – kunif Feb 10 '21 at 01:53

1 Answers1

0

You could download devcon.exe as explained here.
If you are brave enough, you could trust DevCon Installer.

Then, run something like the following from within your code:

    Process p= new Process();

    p.StartInfo.FileName   = "devcon.exe";
    p.StartInfo.Arguments = "disable *SanDisk*";

    p.Start();

My example disconnects a SanDisk USB flashdrive. But this should be able to disconnect any USB device.

How to find the devices for specific ports is explained here:

devcon.exe FindAll =Ports

Some sub-commands of devcon.exe do require administrative privileges.

Axel Kemper
  • 10,544
  • 2
  • 31
  • 54
  • Okay that's great but how can I get devices on COM4. – moe1792 Feb 09 '21 at 21:27
  • I tried this and got an error `System.ComponentModel.Win32Exception: 'The system cannot find the file specified'` I wonder what's gone wrong for me. Error persists even if I type in the complete path to devcon.exe... – monkey May 09 '22 at 05:04