我有一个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();
}
}
我的代码在读写方面有什么问题吗?
如何解决这个问题?
发布于 2010-08-10 19:14:44
您需要确保服务和阅读器都以非独占方式打开日志文件。试试这个:
对于服务-示例中的编写器-使用如下所示创建的FileStream
实例:
var outStream = new FileStream(logfileName, FileMode.Open,
FileAccess.Write, FileShare.ReadWrite);
对于读取器,使用相同的,但更改文件访问:
var inStream = new FileStream(logfileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
此外,由于FileStream
实现了IDisposable
,因此请确保在这两种情况下都要考虑使用using
语句,例如,对于编写器:
using(var outStream = ...)
{
// using outStream here
...
}
祝好运!
发布于 2010-08-10 19:13:25
在读取文本文件时显式设置共享模式。
using (FileStream fs = new FileStream(logFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
while (sr.Peek() >= 0) // reading the old data
{
AddLineToGrid(sr.ReadLine());
index++;
}
}
}
发布于 2010-08-10 19:15:19
new StreamReader(File.Open(logFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
->这不会锁定文件。
https://stackoverflow.com/questions/3448230
复制相似问题