title: Read all buffer data from serial port with C#
body: <p>I have some problems using System.IO.Ports in C# to read data from a serial port. The only method thar works is the "Read" method, but it only read "defined" number of characters and i need to read all available data like "Tera Term" or "Hercules" do. Here is my DLL method that reads the buffer:</p>
  
  <pre><code>public String ReadMessage(String port, int timeout, int dataSize)
  {
      String res;
  
      try
      {
          _serial_port = new SerialPort();
          _serial_port.PortName = port;
          _serial_port.BaudRate = 19200;
          _serial_port.Parity = Parity.None;
          _serial_port.DataBits = 8;
          _serial_port.StopBits = StopBits.One;
          _serial_port.Handshake = Handshake.None;
          _serial_port.ReadTimeout = timeout;
          _serial_port.DtrEnable = true;
          _serial_port.RtsEnable = true;
  
          _serial_port.Open();
          _serial_port.DiscardInBuffer();
  
          int totalBytes = _serial_port.BytesToRead;
  
          if (totalBytes &gt; 0)
          {
              byte[] buffer = new byte[totalBytes];
              _serial_port.Read(buffer, 0, totalBytes);
              res = ByteArrayToString(buffer);                   
          }
          else
          {
              byte[] buffer = new byte[dataSize];
  
              for (int len = 0; len &lt; buffer.Length;)
              {
                  len += _serial_port.Read(buffer, len, buffer.Length - len);
              }
  
              res = ByteArrayToString(buffer);                    
          }
  
          _serial_port.Close();
  
          return res;
      }
      catch (Exception ex)
      {
          if (ex is UnauthorizedAccessException || ex is TimeoutException)
          {
              _serial_port.Close();
          }
  
          return ex.ToString();
      }
  }
  </code></pre>
  
  <p>I know there are other methods to read data like: "ReadByte", "ReadChar", "ReadExisting", "ReadLine" and "ReadTo" but none of them are working, am i doing something wrong?</p>