简体   繁体   English

使用Excel或记事本读取日志文件时写入日志文件

[英]Writing log file while reading it with Excel or Notepad

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. 我想做的就是在运行此代码时用Excel或记事本读取它。 I can open the file externally with Excel, but the file is empty until I stop the program. 我可以使用Excel从外部打开文件,但是在停止程序之前该文件为空。 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 . 此外,当我尝试使用Excel打开它时,尽管我使用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 在while循环中写入文件时,如果要实时查看数据(例如在NotePad ,则需要立即Flush the data ,这很简单

file.Flush(); 

inside of the while loop after the file.Write will work 在文件之后的while循环内。 file.Write将起作用

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();
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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