该进程无法访问该文件,因为当我计数时,它正被另一个进程使用
本文关键字:进程 另一个 访问 文件 因为 | 更新日期: 2023-09-27 18:37:16
我已经构建了一个文件系统观察器解决方案,并且,我会检索对日志文件所做的更改,仅提取添加的行,但我不能这样做,因为我总是错误该进程无法访问该文件,因为它正被另一个进程使用。我的代码是这个检索添加的行是这样的:
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();
}
您不能在FileStream
中打开文件,然后通过 File.ReadLines
访问它,因为FileStream
会锁定文件。我会更改完整的代码。