• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

how to tail a log file using C# and win forms

Joined
Nov 26, 2006
Messages
620
Ok I am NOT looking for an existing log viewing program... But I am looking for how to implement this inside my own C# winforms desktop application. Any helps or suggestions would be great!

Ok I am making a log viewer that has to meet the following requirements.

1. Starts capturing log entries at the end of the file instead of beginning (so only new stuff gets added to my viewer). Currently it starts at the beginning.

2. Does not lock the log file when the log viewer is reading it. Currently it locks the log file with the log viewer is running.

3. Scrolls to the bottom when not in focus, but allows me to scroll when it focus. Currently it auto scrolls to the bottom whether in focus or not... which means I have to stop the log output in order to scroll. I need to be able to scroll up the rich text box while new info is still being written to the bottom.

Here's my code snippet... (some of the variables are instantiated outside this block... don't worry about them, you should be able to see what I am trying to do.)

Code:
if (_log_type == "server_log")
{

    FileStream _log_stream = new FileStream("C:\\server_history.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);


    StreamReader _stream_reader = new StreamReader(_log_stream);


    time_stamp = DateTime.Now.ToString();


    _log_display_box.AppendText("\r\nBegin Log Capture @ " + time_stamp + "\r\n\r\n");

    while (_log_is_paused == false)
    {
        _log_display_box.AppendText(_stream_reader.ReadToEnd());
        _log_display_box.ScrollToCaret();
        await Task.Delay(50);
    }


    time_stamp = DateTime.Now.ToString();


    _log_display_box.AppendText("\r\n\r\nEnd Log Capture @ " + time_stamp + "\r\n");
}
 
1. FileStream.Seek() and seek to the end

2. It looks like FileShare.ReadWrite is what you want... but you have it set. Perhaps whatever you're trying to open it with while your program is using it is requesting exclusive access?

3. AppendText() will scroll it automatically it looks like. Maybe just append to the Text property instead when you have focus? Kinda quirky.
 
Back
Top