2

I'm trying to append new lines in the text box from a log file, the log file gets updated frequently. I have a FileSystemWatcher which checks for any updates in the file and triggers on onChange() event .

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

This will fetch the contents of the entire file , as the log size grows this operation is getting slower and slower . How to read the updated lines instead of the whole file ?

Server will update the list of newly logged in users to the log, for instance there are 15 lines of text in the file and in the text box , after every new log in the server will update the file , i just need to read the 16th line .

nsivaram90
  • 141
  • 1
  • 1
  • 11

1 Answers1

4

I think you would have to keep track of the last position you read from in the file, then when you detect a change: open the file, seek to the proper location, and read to the end. Then parse that into lines to add to the textbox.

Edit: Here is a working console application that demonstrates this. You would want a lot more error checking, initialization, and so on. The old code was just a guess, but was basically right.

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;
            }
        }
    }
}
Andrew
  • 8,322
  • 2
  • 47
  • 70