Continuously writing received data from serial to textfile.

Joined
Jan 31, 2021
Messages
10
Programming Experience
Beginner
Hi there,

For my project, I'm looking for a resolution for my problem. Every second I got a new data from my serial port. When I want to write this to a file, I only get one time the data that has been written.
What Do I have to to to fix this, a program code would be helpfull.
Kind regards and many Thx!
StartWriteData:
private void BttnStartDataWriting_Click(object sender, RoutedEventArgs e)
        {
            
            string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            TxtBlck_DataWritingStart.Text = "Writing to: " + folderPath;

            string filePath = System.IO.Path.Combine(folderPath, "SavedDataDigitaleTeller.csv");
            StreamWriter writer = File.CreateText(filePath);
            string DataLoggerText = String.Format("{0} A", seriëleTelegram.StroomFaseR / 100); // is just one of my received data from my serial
            writer.WriteLine(DataLoggerText);
            writer.Close();

        }

There are about 20 lines of data in my program, so every time the data changes (every second) it has to put this data in a new line in my csv file.
Many thx!
 
Last edited by a moderator:

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,197
Location
Norway
Programming Experience
10+

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,921
Location
Sydney, Australia
Programming Experience
10+
@JohnH is quite correct that calling CreateText rather than AppendText is going to overwrite existing data instead of add to it but you really shouldn't be using either. If all you're doing is opening the file, writing some text and then closing the file again, you should be calling WriteAllText to overwrite or AppendAllText to append. That will do the open, write and close in the a single method call.

That assumes that you're writing infrequently enough that opening and closing the file repeatedly is not a significant overhead. Generally you don't want to keep things like files open for long periods but if you're writing very frequently then you may need to open the file once and keep writing to it, not closing it until your app is done with it. That may restrict you from accessing the file elsewhere while the app is running. You might need to do some testing to determine which option is best.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,386
Location
Chesapeake, VA
Programming Experience
10+
Also, you probably don't want that logic for writing into the file as part of a button click handler as you have above. You'll likely want it as part of the data available serial port event handler.
 
Top Bottom