【问题标题】:The process cannot access the file because it is being used by another process when I count该进程无法访问该文件,因为当我计数时它正被另一个进程使用
【发布时间】: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


【解决方案1】:

您不能在FileStream 中打开文件,然后通过File.ReadLines 访问它,因为FileStream 锁定了文件。我会更改完整的代码。

【讨论】:

  • 能否请您给我一些建议,告诉我如何在不使用File.ReadLines 的情况下实现我的目标?谢谢
猜你喜欢
  • 2010-12-10
相关资源
最近更新 更多