I have a program that requires serial port connection to be open from the moment software the starts up until it's shutdown.
my program starts when the computer starts(it has a shortcut in %startup% folder - windows 7).
I'm using process explorer(by Sysinternals to monitor my serial port). When everything works i do see my open port in there. but sometime after a computer opens up(after normal app closing) im getting the error Access to the port 'com1' is denied and all i see in the process explorer is SMSvcHost.exe
this is open serial connection method
static class CVFeedSerialUtilsV2
{
static string com = GetSerialPortComName();
const int sleepTimeInMs = 50;
private static SerialPort port = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
public static SerialPort Port
{
get { return port; }
}
public static void readAndOpenSerialPort()
{
try
{
if (String.IsNullOrEmpty(com))
{
return;
}
if (port != null && port.IsOpen)
port.Close();
if (!port.IsOpen)
{
port.DtrEnable = true; // Data-terminal-ready
port.RtsEnable = true; // Request-to-send
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
}
}
}
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//do stuff
}
}
and this is my form closing method
private void frmBase_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
//wait for some amount of time after calling the Close method before attempting to call the Open method,
//as the port may not be closed instantly.
if (CVFeedSerialUtilsV2.Port != null && CVFeedSerialUtilsV2.Port.IsOpen)
{
CVFeedSerialUtilsV2.Port.DiscardInBuffer();
CVFeedSerialUtilsV2.Port.DiscardOutBuffer();
CVFeedSerialUtilsV2.Port.DataReceived -= CVFeedSerialUtilsV2.port_DataReceived;
CVFeedSerialUtilsV2.Port.Close();
//CVFeedSerialUtilsV2.Port.Dispose();
}
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
}
}
and this is how i get the serial port
private static string GetSerialPortComName()
{
try
{
List<string> list = new List<string>();
string name = "";
ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject mo2 in searcher2.Get())
{
if (mo2["Name"] != null)
{
name = mo2["Name"].ToString();
// Name will have a substring like "(COM12)" in it.
if (name.Contains("(COM"))
{
list.Add(name);
}
}
}
// remove duplicates, sort alphabetically and convert to array
string[] usbDevices = list.Distinct().OrderBy(s => s).ToArray();
foreach (String s in usbDevices)
{
if (s.ToLower().Contains("port"))
{
int start = s.IndexOf("(COM") + 1;
if (start >= 0)
{
int end = s.IndexOf(")", start + 3);
if (end >= 0)
{
// cname is like "COM14"
return s.Substring(start, end - start);
}
}
}
}
}
catch (Exception ex)
{
}
return "";
}