2013-09-25 35 views
2

我試圖在日誌文件的文本框中附加新行,日誌文件經常更新。我有一個FileSystemWatcher它檢查文件中的任何更新並觸發onChange()事件。如何在由C#中的服務器更新的文件中追加文本框中的更新行?

textbox1.Text = File.ReadAllText(@"D:\Serverlogs\clientList.log");

這將獲取整個文件的內容,作爲日誌大小增長這一操作是越來越慢。如何閱讀更新的行而不是整個文件?

服務器會將新登錄的用戶列表更新爲日誌,例如文件中和文本框中有15行文本,每次在服務器中新建一個日誌後都會更新文件,我只需要閱讀第16行。

+0

如何區分更新後的行? – Damith

回答

4

我認爲你必須跟蹤你在文件中讀取的最後一個位置,然後當你檢測到一個變化時:打開文件,尋找正確的位置,並讀到最後。然後將其解析成行以添加到文本框中。

編輯:這是一個工作控制檯應用程序,演示了這一點。你會想要 更多的錯誤檢查,初始化等。舊代碼只是一個猜測,但基本上是正確的。

class Program 
{ 
    static FileSystemWatcher fs = null; 
    static string fileName = @"c:\temp\log.txt"; 
    static long oldPosition = 0; 

    static void Main(string[] args) 
    { 
     fs = new FileSystemWatcher(Path.GetDirectoryName(fileName)); 
     fs.Changed += new FileSystemEventHandler(fs_Changed); 
     fs.EnableRaisingEvents = true; 
     Console.WriteLine("Waiting for changes to " + fileName); 
     Console.ReadLine(); 
    } 

    static void fs_Changed(object sender, FileSystemEventArgs e) 
    { 
     if (e.FullPath != fileName || e.ChangeType != WatcherChangeTypes.Changed) return; 
     using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
     using (StreamReader fr = new StreamReader(fs)) 
     { 
      Console.WriteLine("{0} changed. Old Postion = {1}, New Length = {2}", e.Name, oldPosition, fs.Length); 
      if (fs.Length > oldPosition) 
      { 
       fs.Position = oldPosition; 
       var newData = fr.ReadToEnd(); 
       Console.WriteLine("~~~~~~ new data ~~~~~~\n" + newData); 
       oldPosition = fs.Position; 
      } 
     } 
    } 
} 
相關問題