title: Writing data to text file
body: <p>I am sending and receiving data using COM port (serial). I have written the following code. This is actually my first <code>C#</code> project as I am kinda new to it. I am trying to write the received data to the text file on my desktop, the program actually creates the file but writes nothing in it. Similarly, I am able to see the received data on the console but it is not being written to the text file. Any help on what I am doing wrong will be much appreciated.</p>
  
  <p>Thank you. The code is below.</p>
  
  <pre><code>class Program
  {
      SerialPort p = new SerialPort("COM7", 300, Parity.None, 8, StopBits.One);
      string sbuffer = string.Empty;
      byte i = 0;
      static void Main(string[] args)
      {
          new Program();
      }
  
      Program()
      {
          string[] names = SerialPort.GetPortNames();
          Console.WriteLine("Serial ports:");
          foreach (string name in names)
          {
              Console.WriteLine(name);
          }
          Console.WriteLine("Using COM7");
  
          p.Open();
  
  
          string data_ = "$1RB\r";
          Console.WriteLine("Writing data: {0}",data_);
          p.Write(data_);
          p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
          Console.ReadKey();
          p.Close();
      }
  
  
      void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
          Thread.Sleep(5);
          sbuffer += (sender as SerialPort).ReadExisting();
          i++;
          if (i &gt; 9)
          {
              Console.WriteLine(sbuffer);
            System.IO.File.WriteAllText(@"C:\Users\myname\Desktop\WriteText.txt", sbuffer);
              sbuffer = string.Empty;
          }
      }
  }
  </code></pre>
  
  <p>}</p>