Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 进程无法访问该文件,因为我计数时另一进程正在使用该文件_C#_.net_Winforms_Filesystemwatcher - Fatal编程技术网

C# 进程无法访问该文件,因为我计数时另一进程正在使用该文件

C# 进程无法访问该文件,因为我计数时另一进程正在使用该文件,c#,.net,winforms,filesystemwatcher,C#,.net,Winforms,Filesystemwatcher,我已经构建了一个文件系统监视程序解决方案,并且,我希望检索对日志文件所做的更改,只提取添加的行,但是我不能这样做,因为我总是错误地认为进程无法访问该文件,因为它正被另一个进程使用。 我的代码是检索添加的行的代码是: using (var file = new FileStream(FileName, FileMode.Open, File

我已经构建了一个文件系统监视程序解决方案,并且,我希望检索对日志文件所做的更改,只提取添加的行,但是我不能这样做,因为我总是错误地认为进程无法访问该文件,因为它正被另一个进程使用。 我的代码是检索添加的行的代码是:

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

在继续之前,请重命名控件。listbox1不是一个好的命名约定。顺便说一句,使用空的catch{}块与您的问题无关,但接受异常是不好的做法。在catch blockSee上添加处理以获得正确的实现。你的代码有很多错误。谢谢你的宝贵建议。我是个新手。请给我一个从现在开始的示例代码好吗?再次提前感谢。为了更清楚,在我的代码片段中,我会尝试选择像SQL steatement一样,仅使用“LinecountStartPositionBUFF”和“LinecountEndPosition”添加的行。请您就如何实现不使用File.ReadLines的目标给我一些建议?非常感谢。