I am sending and receiving data using COM port (serial). I have written the following code. This is actually my first C# 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.
Thank you. The code is below.
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 > 9)
{
Console.WriteLine(sbuffer);
System.IO.File.WriteAllText(@"C:\Users\myname\Desktop\WriteText.txt", sbuffer);
sbuffer = string.Empty;
}
}
}
}
You could use events, or simply use this method and pass your data string to it. It will simply append to the file as long as it exists, or create a new file if it does not. The data written should be identical to whatever output is appearing in your console screen.