2013-09-25 31 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; 
      } 
     } 
    } 
} 
相关问题