Reputation: 3813
I have a program that talks to an embedded device over USB. Sometimes, I need to reboot this device and have it enumerate as a new VCOM, and then reboot without this VCOM. So the way I'm doing this right now is (with superfluous .ToArray()
for debug purposes):
string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
Trace.WriteLine("old ports: " + string.Join(", ", portNames));
// Reboot
string[] newPorts = System.IO.Ports.SerialPort.GetPortNames().Except(portNames).ToArray();
Trace.WriteLine("new ports: " + string.Join(", ", newPorts));
if (newPorts.SingleOrDefault() != null){/* connect to the new port if there's exactly one*/}
//...
//...
// Reboot with without VCOMM.
Now this works all fine and good the FIRST time I run it. However, the registry entry that SerialPort.GetPortNames
points to (HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
) doesn't remove the old COM port once it's disconnected. Device manager, however, does.
So the second time I run that code, I get that there's no new devices connected after reboot, which breaks everything. Is there any way I can force a refresh/flush of that registry entry or just grab whatever devices are in device manager?
EDIT: The strange thing is when I close my program, the entry in the registry goes away. But I'm closing and removing references to the SerialPort object that I create (and I tried calling both .Close()
and .Dispose()
). I checked and there's no SerialPort objects in managed memory.
Upvotes: 1
Views: 1550
Reputation: 3813
I figured out my problem. It has to do with the way I released the serial port. If you try to close a serial port when it doesn't exist anymore (ie, i already rebooted my device off of that VCOM), it'll throw an error. If you don't catch the error, it'll stick around in the registry until the program ends.
For posterity, here's what I did:
private SerialPort m_Port = null;
public void Close()
{
try
{
if (m_Port.IsOpen)
{
m_Port.Close();
}
}
catch(Exception ex) { Trace.WriteLine(ex.Message); }
m_Port = null;
}
Upvotes: 1