Find and Replace Text in a Large TextFile (Delphi XE5)
<p>I am trying to find and replace text in a text file. I have been able to do this in the past with methods like:</p>

<pre><code>procedure SmallFileFindAndReplace(FileName, Find, ReplaceWith: string);
begin
  with TStringList.Create do
    begin
    LoadFromFile(FileName);
    Text := StringReplace(Text, Find, ReplaceWith, [rfReplaceAll, rfIgnoreCase]);
    SaveToFile(FileName);
    Free;
  end;
end;
</code></pre>

<p>The above works fine when a file is relatively small, however; when the the file size is something like 170 Mb the above code will cause the following error:
EOutOfMemory with message 'Out of memory'<a href="https://i.stack.imgur.com/bhQez.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bhQez.png" alt="enter image description here"></a></p>

<p>I have tried the following with success, however it takes a long time to run:</p>

<pre><code>procedure Tfrm_Main.button_MakeReplacementClick(Sender: TObject);
var
  fs : TFileStream;
  s  : AnsiString;
  //s  : string;
begin
  fs := TFileStream.Create(edit_SQLFile.Text, fmOpenread or fmShareDenyNone);
  try
    SetLength(S, fs.Size);
    fs.ReadBuffer(S[1], fs.Size);
  finally
    fs.Free;
  end;
  s := StringReplace(s, edit_Find.Text, edit_Replace.Text, [rfReplaceAll, rfIgnoreCase]);
  fs := TFileStream.Create(edit_SQLFile.Text, fmCreate);
  try
    fs.WriteBuffer(S[1], Length(S));
  finally
    fs.Free;
  end;
end;
</code></pre>

<p>I am new to "Streams" and working with buffers.</p>

<p><b>Is there a better way to do this?</b></p>

<p>Thank You.</p>