/// <summary> /// Open the port specified by the Port property. /// </summary> public void Open() { if (IsDisposed) { throw new ObjectDisposedException("NativeSerialPort"); } if (string.IsNullOrWhiteSpace(m_Port)) { throw new InvalidOperationException("Port must first be set"); } if (IsOpen) { throw new InvalidOperationException("Serial Port currently open"); } m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + m_Port, NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE, NativeMethods.FileShare.FILE_SHARE_NONE, IntPtr.Zero, NativeMethods.CreationDisposition.OPEN_EXISTING, NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (m_ComPortHandle.IsInvalid) { WinIOError(); } NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle); if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN) { m_ComPortHandle.Close(); m_ComPortHandle = null; throw new IOException("Wrong Filetype: " + m_Port); } // Set the default parameters UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue); m_CommState = new CommState(m_ComPortHandle, m_CommState); m_CommProperties = new CommProperties(m_ComPortHandle); m_CommModem = new CommModemStatus(m_ComPortHandle); CommOverlappedIo commIo = new CommOverlappedIo(m_ComPortHandle, m_CommIo, Port); m_CommIo.Dispose(); m_CommIo = commIo; }
/// <summary> /// Closes the serial port. /// </summary> /// <exception cref="System.ObjectDisposedException"/> /// <remarks> /// Closing the serial port invalidates actions that can be done to the serial port, /// but it does not prevent the serial port from being reopened /// </remarks> public void Close() { if (m_IsDisposed) { throw new ObjectDisposedException("WinNativeSerial"); } if (IsOpen) { m_CommOverlappedIo.Dispose(); m_CommOverlappedIo = null; m_CommState = null; m_CommModemStatus = null; m_ComPortHandle.Dispose(); m_ComPortHandle = null; } }