简体   繁体   中英

Writing data to text file

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.

    static void WriteOutputToTextFile(string _data)
    {
        string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);   //set destination as your desktop
        using (StreamWriter SW = new StreamWriter(FolderName + "\\test.txt", true))   //true makes it append to the file instead of overwrite
        {
            SW.WriteLine(_data);
            SW.Close();
        }
    }

You are opening and overwriting the same file again and again. Use the FileStream (or even better, StreamWriter) class instead, keep the stream open together with the serial port and close it when you're done.

Also, if you transmit text via the serial port, you might want to consider the SerialPort.ReadLine() method that is much easier to use.

Extending @Alan's answer, you can use File.AppendAllText instead of File.WriteAllText which will overwrite the file again and again. So if you receive empty text before you check the file, the file will be overwritten with empty text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM