【发布时间】:2015-01-13 11:14:04
【问题描述】:
我已经构建了一个文件系统观察器解决方案,并且,我想检索对日志文件所做的更改,只提取添加的行,但我不能这样做,因为我总是错误地认为进程无法访问文件,因为它正被另一个进程使用。 我的代码是这样的,用于检索添加的行是这样的:
using (var file = new FileStream(FileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read))
using (var sr = new StreamReader(file))
{
try
{
Thread thread = new Thread(delegate()
{
listBox1.Invoke((MethodInvoker)(() =>
{
listBox1.Items.Clear();//this is the listbox that list every added line and that I clear before of to be filled
string[] lines = File.ReadLines(fileName)
.Skip(LinecountStartPositionBUFF)
.Take(LinecountEndPosition - LinecountStartPositionBUFF)
.ToArray();
listBox1.Items.AddRange(lines);
}));
});
thread.Start();
while (thread.IsAlive)
Application.DoEvents();
}
catch
{ }
return sr.ReadLine();
}
【问题讨论】:
-
在您继续之前,请重命名您的控件。 (
listbox1不是一个好的命名约定)。顺便说一句,也没有使用空的catch {}块 -
与您的问题无关,但吞下异常是不好的做法。在你的 catch 块上添加处理
-
请参阅Read last line of text file 以获得正确的实现。你的代码有很多问题。
-
感谢您的宝贵建议。我是新手。我可以有一个示例代码来开始吗?再次提前感谢。
-
为了更清楚起见,在我的 sn-p 中,我会尝试选择 SQL 语句,仅使用 'LinecountStartPositionBUFF' 和 'LinecountEndPosition' 添加的行。
标签: c# .net winforms filesystemwatcher