2014-01-29 65 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

相關問題