title: Building a large file text-editor
body: <p>So I'm building my own custom-drawn large text edit control, which I want to be able to open a large text file, and only a small chunk of it. I am able to successfully do that, but the problem is large lines. I have it so that every time I read a char (which shouldn't be too many as it's limited to the size of the screen), it will measure the length of that line. If it's greater than the width of the screen, it will stop rendering that line. However, I still have to find the position of the next line which means having to read that line (which could be hundreds of GB large). Here is my code so far:</p>
  
  <pre><code>if (encoding == Encoding.ASCII || encoding == Encoding.Default)
  {
      fileStream.Seek(visibleLinesRanges[0].Start, SeekOrigin.Begin);
      int maxNumberLines = MaxLinesOnScreen;
      int linesRead = 0;
  
      int read;
      byte[] byteBuffer = new byte[bufferSize];
      StringBuilder text = new StringBuilder();
      string lineText = string.Empty;
      bool dontAddLine = false;
  
      void AddLine()
      {
          if (dontAddLine)
          {
  lineText = string.Empty;
  return;
          }
          linesRead++;
          bool visible = linesRead &gt;= maxNumberLines;
  
          if (vScrollBar.Visible != visible)
          {
  vScrollBar.Visible = visible;
          }
          text.Append(lineText);
          lineText = string.Empty;
      }
  
      while ((read = fileStream.Read(byteBuffer, 0, bufferSize)) &gt; 0)
      {
          char[] charBuffer = encoding.GetChars(byteBuffer, 0, read);
  
          for (int i = 0; i &lt; read; i++)
          {
  char c = charBuffer[i];
  
  if (!dontAddLine)
  {
      string newLineText = lineText + c;
  
      if (TextRenderer.MeasureText(newLineText, Font).Width &gt; Width)
      {
          lineText += "\n";
          AddLine();
          if (linesRead &gt; maxNumberLines)
          {
  goto Drawing;
          }
          dontAddLine = true;
      }
      else
      {
          lineText = newLineText;
      }
  }
  
  if (c == '\r')
  {
      char c1 = ReadCharSingle(charBuffer, i, read);
      if (c1 != '\n')
      {
          AddLine();
          if (linesRead &gt; maxNumberLines)
          {
  goto Drawing;
          }
          dontAddLine = false;
      }
  }
  else if (c == '\n')
  {
      AddLine();
      if (linesRead &gt; maxNumberLines)
      {
          goto Drawing;
      }
      dontAddLine = false;
  }
          }
      }
  Drawing:
      TextRenderer.DrawText(g, text.ToString(), Font, Point.Empty, Color.Gainsboro);
  }
  </code></pre>
  
  <p>This works, and barely uses any memory, but the problem is that it's very slow when opening a file with a single line that is about ~120MB in size. Also, whenever I resize the window, I have to call this code (in the <code>Paint</code> event), so that the text is updated.
  This is very slow. Is there any way to speed this up? Thanks.</p>