Friday, December 2, 2011

System.UnauthorizedAccessException: Access to the port is denied

This exception can occur in an application that is communicating with a USB device via a System.IO.Ports.SerialPort object. If the USB cable is unplugged before SerialPort.Close() is called, this unhandled exception will be thrown and cannot be caught. Ultimately, the application will crash. This issue has been reported to Microsoft here.

There are three possible ways to resolve this issue:
  1. Step up to .NET Framework 4 where this issue no longer occurs.

  2. Use the workaround supplied by Microsoft:

    Revert to the .NET Framework 1.1 behavior and catch the exception. To do this, set the legacyUnhandledExceptionPolicy in the application config file, as in the following example:

    <configuration>
      <runtime> 
        <legacyUnhandledExceptionPolicy enabled="1"/>
      </runtime>
    </configuration>

  3. Solution #2 does not apply to .NET Framework 3.5. While it does prevent the application from crashing, the exception still cannot be caught. In this case, suppress the finalization of the SerialPort BaseStream, as in the following example:

    SerialPort _SerialPort;
    Stream
    _SafeBaseStream;

    public
    void Open()
    {
       
        _SerialPort.Open();
       
        _SafeBaseStream = _SerialPort.BaseStream;

    }


    public
    void Close()
    {
        if
    (_SerialPort.IsOpen)
            _SerialPort.Close();
        else
            GC.SuppressFinalize(_SafeBaseStream);

        _SerialPort = null;
        _SafeBaseStream = null;
    }

    Just note that using this may result in BaseStream leaking resources.