title: C# Serial Port Write Byte
body: <p>Writing a single byte to the serial port in .NET 4.0  in C# causes a </p>
  
  <blockquote>
    <p>InvalidOperationException was unhandled by user code</p>
  </blockquote>
  
  <p>Every time a byte is sent to the SerialPort. </p>
  
  <p>How do I write a single byte to the serial port?</p>
  
  <pre><code>    //Serial Init
      //Full fledged constuctor
      public NetCommManager(String portName, TransmissionType trans, String baud, String parity, String stopBits, String dataBits)
      {
          nc_baudRate = baud;
          nc_parity = parity;
          nc_stopBits = stopBits;
          nc_dataBits = dataBits;
          nc_portName = portName;
          nc_transType = trans;
  
          //now add an event handler
          comPort.DataReceived += new SerialDataReceivedEventHandler(netComm_DataReceived);
      }
  </code></pre>
  
  <p>Config:</p>
  
  <pre><code>       _commManger = new NetCommManager(commPortNumber,                        
         NetCommManager.TransmissionType.Text, "19200", "None", "One", "8");
  </code></pre>
  
  <p>The Byte to be written:</p>
  
  <pre><code>_commManager.WriteByte(Convert.ToByte( 0x7B));
  </code></pre>
  
  <p>And <code>WriteByte</code> function is:</p>
  
  <pre><code>public void WriteByte(byte data)
          {
              //change data to array
              //byte[] dataArray = new byte[1];
              var dataArray = new byte[] {data};
              //dataArray[0] = data;
              comPort.Write(dataArray, 0, 1);   // &lt;-- Exception is thrown here
          }
  </code></pre>
  
  <p>The NetCommManager class is very much based on <a href="http://www.dreamincode.net/forums/topic/35775-serial-port-communication-in-c%23/" rel="nofollow noreferrer">this example</a></p>