该进程无法访问该文件,因为当我计数时它正在被另一个进程使用

The process cannot access the file because it is being used by another process when I count

我已经构建了一个 File System Watcher 解决方案,并且我想检索对日志文件所做的更改,只提取添加的行,但我不能这样做,因为我总是错误说进程无法访问文件,因为它正被另一个进程使用。 我的代码是这样的,用于检索添加的行是这样的:

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 锁定了文件。我会更改完整的代码。