I am making a program that controls a game server. One of the features that I create is the real-time log log monitor.
There is a log file (plain text file) that is updated by the server as it runs.
How can I constantly check the log file and display its contents in a RichTextBox?
I made this simple function, just try and get the contents of the log. Of course, it will be just text on a line and display it in a text field. It will also block the program as long as the loop is running, so I know this is useless.
public void ReadLog() { using (StreamReader reader = new StreamReader("server.log")) { String line; // Read and display lines from the file until the end of the file is reached. while ((line = reader.ReadLine()) != null) { monitorTextBox.AppendText(line + "\n"); CursorDown(); } } }
But how would you decide to solve live monitoring as easily as possible?
* EDIT *
I am using Prescots solution. great stuff.
I am currently using sreadreader to put text from a file into a text box. I ran into a problem in that whenever I tried to access any gui control in an event handler, the program simply stopped without errors or warnings.
I found out that this is related to threads. I decided like this:
private void OnChanged(object source, FileSystemEventArgs e) { if (monitorTextField.InvokeRequired) { monitorTextField.Invoke((MethodInvoker)delegate { OnChanged(source, e); }); } else { StreamReader reader = new StreamReader("file.txt"); monitorTextField.Text = ""; monitorTextField.Text = reader.ReadToEnd(); reader.Close(); CursorDown(); } }
Now my only problem is that the .txt file is being used by the server, so I can’t access it because it is “being used by another process”. I can not control this process. Maybe I'm out of luck.
But the file can be opened in notepad while serevr is running, so somehow it should be possible. Perhaps I can make a temporary copy of the file when it updates and reads the copy. Dunno ...