title: How to monitor Textfile and continuously output content in a textbox?
body: <p>I'm making a program that controls a game server. One of the functions I'm making, is a live server logfile monitor.</p>
  <p>There is a logfile (a simple textfile) that gets updated by the server as it runs.</p>
  <p>How do I continuously check the logfile and output it's content in a RichTextBox?</p>
  <p>I did this simple function just try and get the content of the log. It will of course just get the text row by row and output it to my textbox. Also it will lock the program for as long as the loop runs, so I know it's useless.</p>
  <pre><code>public void ReadLog()
  {
    using (StreamReader reader = new StreamReader(&quot;server.log&quot;))
    {
      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 + &quot;\n&quot;);
        CursorDown();
      }
    }
  }
  </code></pre>
  <p>But how would you go about solving the live monitoring as simple as possible?</p>
  <p>*** EDIT ***</p>
  <p>I'm using Prescots solution. great stuff.</p>
  <p>At the moment I'm using a sstreamreader to put the text from the file to my textbox.  I ran into the problem is that, whenever I tried to access any of the gui controls in my event handler the program just stopped with no error or warnings.</p>
  <p>I found out that it has to do with threading. I solved that like this:</p>
  <pre><code>private void OnChanged(object source, FileSystemEventArgs e)
  {
      if (monitorTextField.InvokeRequired)
      {
          monitorTextField.Invoke((MethodInvoker)delegate { OnChanged(source, e); });
      }
      else
      {
        StreamReader reader = new StreamReader(&quot;file.txt&quot;);
  
        monitorTextField.Text = &quot;&quot;;
        monitorTextField.Text = reader.ReadToEnd();
        reader.Close();
        CursorDown();
      }
  }
  </code></pre>
  <p>Now my only problem is that the file.txt is used by the server so I can't access it, since it's &quot;being used by another process&quot;. I can't control that process, so maybe I'm out of luck.</p>
  <p>But the file can be opened in notepad while the server is running, so somehow it must be possible. Perhaps I can do a temp copy of the file when it updates and read the copy. I don't know.</p>