I'm writing to a log file with this stream :
using(FileStream fs = new FileStream(Path.Combine(Folder, LogFile),
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.ReadWrite))
{
using(System.IO.StreamWriter file = new System.IO.StreamWriter(fs))
{
while(!token.IsCancellationRequested)
{
file.WriteLine("bla bla bla");
}
}
}
The purpose of this code sample is to write into a log file. What I would like to be able to do is to read it with Excel or notepad while this code is running. I can open the file externally with Excel, but the file is empty until I stop the program. Furthermore, when I try to open it with Excel, I am said that the file is locked for editing although I declared the stream with the FileShare.ReadWrite
.
when writing files in a while loop and you want to see the data real time for example in NotePad
you need to immediately Flush the data
in your case a simple
file.Flush();
inside of the while loop after the file.Write
will work
using(FileStream fs = new FileStream(Path.Combine(Folder, LogFile),
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.ReadWrite))
{
using(System.IO.StreamWriter file = new System.IO.StreamWriter(fs))
{
while(!token.IsCancellationRequested)
{
file.WriteLine("bla bla bla");
file.Flush();
}
}
}
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.