2014-01-29 63 views
2

我有一个文本文件,每次从服务器数据中获取更新。现在根据我的要求,我必须逐行读取此文件。我知道如何读取文件行通过线,但没有得到如何看它continuously.Here是我的C#代码逐行读取文件中的行...如何连续读取文本文件

if (System.IO.File.Exists(FileToCopy) == true) 
     { 

      using (StreamReader reader = new StreamReader(FileToCopy)) 
      { 
       string line; 
       string rawcdr; 

       while ((line = reader.ReadLine()) != null) 
       { 
        //Do Processing 
       } 
       } 
     } 

按我的要求我必须不断地观看文本文件changes.Suppose新行已被添加到文本文件中,添加它的那一刻应该被上面定义的代码读取,并且处理应该根据条件来执行。

+0

作为参考,UNIX实用程序['尾-f'](http://stackoverflow.com/questions/1439799/how-can-i-get-the-source-code-for-the- linux-utility-tail)实现了这一点。他们称之为“跟随”一个文件。 –

+0

[c#不断读取文件]的可能重复(http://stackoverflow.com/questions/3791103/c-sharp-continuously-read-file) –

回答

5

可以使用FileSystemWatcher来侦听文件系统更改通知,并在目录或目录中的文件时引发事件。如果文本附加在文本文件中但未被修改,则可以跟踪已读取的行号,并在触发更改事件后继续。

private int ReadLinesCount = 0; 
public static void RunWatcher() 
{ 
    FileSystemWatcher watcher = new FileSystemWatcher(); 
    watcher.Path = "c:\folder";    
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;    
    watcher.Filter = "*.txt";    
    watcher.Changed += new FileSystemEventHandler(OnChanged); 
    watcher.EnableRaisingEvents = true; 

} 

private static void OnChanged(object source, FileSystemEventArgs e) 
{ 
     int totalLines - File.ReadLines(path).Count(); 
     int newLinesCount = totalLines - ReadLinesCount; 
     File.ReadLines(path).Skip(ReadLinesCount).Take(newLinesCount); 
     ReadLinesCount = totalLines; 
} 
+0

在哪里添加此代码在我的发布代码的阅读文本文件.. – Adi

+0

你必须阅读change event上的文件,每次文件改变时你都会得到这个事件。我已经提供了绑定事件和读取行的代码,您必须提供读取行和列表,您需要阅读跳过和采取方法。 – Adil

+0

如何让ReadLinesCount和NewLinesCount读取文件 – Adi

相关问题