public static bool TryCloseSerialPort(ObjectClasses.ISerialPortIo serialPort1, string source) { if (serialPort1.IsOpen == true) { try { serialPort1.Close(); return true; } catch (System.IO.IOException) { DataComms.CreateThreadInstance("TryCloseSerialPort - IOException: " + source); } catch (UnauthorizedAccessException) { DataComms.CreateThreadInstance("TryCloseSerialPort - UnauthorizedAccessException: " + source); } catch (Exception) { DataComms.CreateThreadInstance("TryCloseSerialPort - Exception: " + source); } finally { } return false; } else { return true; } }
public static bool TryOpenSerialPort(ObjectClasses.ISerialPortIo serialPort1, string source) { if (serialPort1.IsOpen == false) { try { serialPort1.Open(); return true; } catch (System.IO.IOException e) { DataComms.CreateThreadInstance("TryOpenSerialPort - IOException: " + source); } catch (UnauthorizedAccessException e) { DataComms.CreateThreadInstance("TryOpenSerialPort - UnauthorizedAccessException " + source); serialPort1.Close(); //serialPort1.Dispose(); //serialPort1 = new SerialPort(); //Logger.Write("UnauthorizedAccessException while trying to open the serial port"); //LblStatus.Text = "UnauthorizedAccessException: Please exit and restart the program"; } catch (Exception) { DataComms.CreateThreadInstance("TryOpenSerialPort - Exception " + source); } finally { } return false; } else { return true; } }