0

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 "";
        }
styx
  • 1,852
  • 1
  • 11
  • 22
  • Does that mean you close the App, then start it again? Or close the App, reboot machine and then start the App during startup? – Fildor Aug 20 '18 at 14:05
  • close the app - > close the machine -> some time passed - > startup the machine -> the program startsup – styx Aug 20 '18 at 14:07
  • Pretty sure you will find that Windows willl close all handles a process has open when the process exits. –  Aug 20 '18 at 14:21
  • @MickyD what do you mean? – styx Aug 21 '18 at 06:09
  • Under Windows, all I/O devices whether they be _"file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe"_ are opened via `CreateFile` which returns a file handle. All handles are closed when the process exits –  Aug 21 '18 at 07:04
  • so why im still getting this error? – styx Aug 21 '18 at 07:19
  • Are you using USB to Serial or are you using a real RS232 port on your PC? – Baddack Aug 21 '18 at 16:05
  • @Baddack real RS232 port – styx Aug 22 '18 at 11:19

0 Answers0