简体   繁体   中英

Text file not updating right away when using TextWriter

I am using TextWriter to write serial data coming every 100ms on a text file. But the text file is not updated right away. Sometimes it takes few seconds and sometimes a minute for the written text to be shown on the .txt file. How can i fix that?

   TextWriter tw;

    tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));
    tw.Write(text);

The data is only written when the relevant buffers are filled. You can force a flush using tw.Flush() , which will push the (partial) data from the TextWriter to the FileStream .

Note that this may have a significant impact on performance, though. Caching and buffering are quite important, since disks are just so much slower than RAM (and RAM is much slower than the CPU). Make sure the cost is worth the benefits, and consider only flushing once in a while anyway.

You need to call flush for any buffered data to be written to the file immediately

 TextWriter tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));
 tw.Write(text);
 tw.Flush();
 tw.Dispose();

or alternatively you can using TextWriter in a using statement which will flush all the buffered data on TextWriter.Dispose, This way you need not to handle Writer.Dispose

using (TextWriter tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));)
{
    tw.Write("test");
}

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