Uncatcheable exception while using SerialPort class in .NET
<p>Does anybody knows problem with UnauthorizedAccessException fixed in .NET Framework 4 or not?</p>

<p><a href="http://www.windowsdevelop.com/windows-forms-general/unauthorizedaccessexception-within-systemioportsserialport-class-18328.shtml" rel="nofollow">http://www.windowsdevelop.com/windows-forms-general/unauthorizedaccessexception-within-systemioportsserialport-class-18328.shtml</a>;</p>

<p>--
Best regards,
Ivan.</p>

<hr>

<p>leppie, Sorry, I did not posted my code. Just look at this.</p>

<pre><code>private void GetMeasure()
    {
        try
        {
            while (_measureGetting)
            {
                SerialPort port = null;
                try
                {
                    if (string.IsNullOrEmpty(_portName))
                    {
                        Thread.Sleep(100);
                        continue;
                    }
                    port = new SerialPort(_portName, 38400);
                    _allDone.Reset();
                    byte[] buffer = Encoding.UTF8.GetBytes(SbitGetKey());
                    _sbitKey = MD5.Create().ComputeHash(buffer);
                    port.Open();
                    if (port.BytesToRead &gt; 0)
                    {
                        SbitReadBinaryData(port);
                    }
                    port.DataReceived += SbitDataReceived;
                    _allDone.WaitOne();
                    port.DiscardInBuffer();
                    port.DiscardOutBuffer();
                    port.BaseStream.Dispose();
                    port.Close();
                    port.Dispose();
                    port = null;
                }
                catch (IOException exception)
                {
                    Logger.Write(exception);
                    port.Close();
                    port.Dispose();
                    port = null;
                }
                catch (UnauthorizedAccessException exception)
                {
                    Logger.Write(exception);
                }
                Thread.Sleep(100);
            }
        }
        catch (Exception exception)
        {
            Logger.Write(exception);
            throw new ThermometerException("Cannot receive data", exception);
        }
    }

private void CheckDevices()
    {
        try
        {
            string oldPort = _portName;
            bool fl = false;

            while (_deviceChecking)
            {
                _portName = FindSbit();

                if (string.IsNullOrEmpty(oldPort) &amp;&amp; string.IsNullOrEmpty(_portName))
                {
                    if (!fl)
                    {
                        OnThermometerDisconnected();
                        fl = true;
                    }
                }
                else if (string.IsNullOrEmpty(oldPort) &amp;&amp; !string.IsNullOrEmpty(_portName))
                {
                    oldPort = _portName;
                    OnThermometerConnected();
                }
                else if (!string.IsNullOrEmpty(oldPort) &amp;&amp; string.IsNullOrEmpty(_portName))
                {
                    oldPort = _portName;
                    OnThermometerDisconnected();
                }
                else if (!string.IsNullOrEmpty(oldPort) &amp;&amp; !string.IsNullOrEmpty(_portName))
                {
                }
                Thread.Sleep(1000);
            }
        }
        catch (Exception exception)
        {
            Logger.Write(exception);
            throw new ThermometerException("Cannot check device status.", exception);
        }
    }

private string FindSbit()
    {
        using (ManagementClass manager = new ManagementClass("Win32_SerialPort"))
        {
            string id = string.Empty;

            EnumerationOptions opt = new EnumerationOptions {EnumerateDeep = true};
            foreach (ManagementObject obj in manager.GetInstances(opt))
            {
                if (obj.Properties["Description"].Value.ToString() == "SBIT")
                {
                    return obj.Properties["DeviceID"].Value.ToString();
                }
            }

            return id;
        }
    }

private void SbitDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            SerialPort port = (SerialPort) sender;
            if (!port.IsOpen)
            {
                return;
            }
            List&lt;byte&gt; buffer = new List&lt;byte&gt;(SbitReadBinaryData(port));
            if (buffer.Count == 0) return;

            // some secret code :)

            _allDone.Set();
        }
        catch (Exception exception)
        {
            Logger.Write(exception);
            throw new ThermometerException("Cannot receive data from Sbit", exception);
        }
    }

private byte[] SbitReadBinaryData(SerialPort port)
    {
        if (port.IsOpen)
        {
            int read, offset = 0;
            byte[] buffer = new byte[port.BytesToRead];
            while (offset &lt; port.BytesToRead &amp;&amp; (read = port.Read(buffer, offset, port.BytesToRead - offset)) &gt; 0)
                offset += read;
            return buffer;
        }
        return null;
    }

private void OnThermometerDisconnected()
    {
        if (Disconnected != null &amp;&amp; _eventsEnabled)
        {
            Disconnected(this, null);
        }
        _connected = false;
        _allDone.Set();
    }
</code></pre>

<p>Function FindSbit() checks if my device was connected or disconnected. It is possible that I get UnauthorizedAccessException while using WMI? I'm running my application with administrative rights (Windows 7).</p>

<p>Sorry for so hard code. I tried to catch exception everywhere without any results.
You can find, that unplugging of device is handled and there is new SerialPort creation after each reading from port stream. OnThermometerDisconnected function has </p>

<p>P. S. It is too hard to reproduce this problem (about 3-5%).</p>
