user6203007
user6203007

Reputation: 33

How to save incoming data from serial port to a text file in C#

I have two buttons on my window.

  1. By clicking the start button I want to open the port and see the data in the textbox and at the same time i want to save this data in Another empty text file line by line.
  2. And by clicking the stop button the program just stops saving the data but still shows the incoming data from serial port in the textbox. Can someone help? My code for start and stop button looks like:

    private void buttonStart_Click(object sender, EventArgs e)
    {
    
        serialPort1.PortName = pp.get_text();
        string Brate = pp.get_rate();
        serialPort1.BaudRate = Convert.ToInt32(Brate);
    
          serialPort1.Open();
    
        if (serialPort1.IsOpen)
        {
            buttonStart.Enabled = false;
            buttonStop.Enabled = true;
            textBox1.ReadOnly = false;
        }
    }
    
    
    private void buttonStop_Click(object sender, EventArgs e)
    {
    
    
        string Fname = pp.get_filename();
        System.IO.File.WriteAllText(Fname, this.textBox1.Text);
    
    
    }
    

Upvotes: 0

Views: 11563

Answers (1)

raidensan
raidensan

Reputation: 1139

1) You need to register to DataRecieved event of serial port to receive response from SerialPort instance.

sp = new SerialPort();
sp.DataReceived += sp_DataReceived;

Then, in sp_DataRecieved:

    void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        // this the read buffer
        byte[] buff = new byte[9600];
        int readByteCount = sp.BaseStream.Read(buff, 0, sp.BytesToRead);
        // you can specify other encodings, or use default
        string response = System.Text.Encoding.UTF8.GetString(buff);

        // you need to implement AppendToFile ;)
        AppendToFile(String.Format("response :{0}",response));

        // Or, just send sp.ReadExisting();
        AppendToFile(sp.ReadExisting());
    }

2) You will receive data if there is still data in read buffer of SerialPort instance. After closing port, you need to deregister from DataReceived event.

sp -= sp_DataRecieved;

UPDATE

You can use this method to append to file

private void AppendToFile(string toAppend)
{
    string myFilePath = @"C:\Test.txt";
    File.AppendAllText(myFilePath, toAppend + Environment.NewLine);
}

Upvotes: 3

Related Questions