2015-01-13 20 views
-3

我已经构建了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(); 
     } 
+0

在您继续之前,请重命名您的控件。 ('listbox1'是**不是一个好的命名约定)。顺便说一句,也没有使用空的“catch {}”块 – jbutler483

+0

与您的问题无关,但吞咽异常是不好的做法。添加处理您的catch块 – apomene

+0

请参阅[读取文本文件的最后一行](http://stackoverflow.com/questions/11625595/read-last-line-of-text-file)以获得正确的实现。你的代码有很多错误。 – CodeCaster

回答

2

无法通过File.ReadLines打开一个FileStream文件并稍后访问它,因为FileStream锁定该文件。我会改变完整的代码。

+0

可否请给我一些关于如何达到我的目标不使用'File.ReadLines'的建议?谢谢 –

相关问题