我有一個Windows服務以簡單格式將其日誌寫入文本文件。如何在不鎖定的情況下讀取文本文件?
現在,我將創建一個小應用程序來讀取服務的日誌,並將現有日誌和添加的日誌顯示爲實時視圖。
問題是,該服務鎖定文本文件以添加新行,同時查看器應用程序鎖定文件以供閱讀。
服務代碼:
void WriteInLog(string logFilePath, data)
{
File.AppendAllText(logFilePath,
string.Format("{0} : {1}\r\n", DateTime.Now, data));
}
觀衆代碼:
int index = 0;
private void Form1_Load(object sender, EventArgs e)
{
try
{
using (StreamReader sr = new StreamReader(logFilePath))
{
while (sr.Peek() >= 0) // reading the old data
{
AddLineToGrid(sr.ReadLine());
index++;
}
sr.Close();
}
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader(logFilePath))
{
// skipping the old data, it has read in the Form1_Load event handler
for (int i = 0; i < index ; i++)
sr.ReadLine();
while (sr.Peek() >= 0) // reading the live data if exists
{
string str = sr.ReadLine();
if (str != null)
{
AddLineToGrid(str);
index++;
}
}
sr.Close();
}
}
是否有閱讀和寫作的方式在我的代碼什麼問題?
如何解決問題?
可能的重複[可以阻止StreamReader鎖定正在使用的文本文件嗎?](https://stackoverflow.com/questions/1606349/can-i-prevent-a-streamreader-from-locking -a-text-file-while-it-in-use) – 2017-09-15 09:49:23