12

Hi I have a problem with replacing a text in a textfile with Inno Setup (Delphi based).

My Code:

procedure  FileReplaceString(const  FileName,  searchstring,  replacestring:  string);
var
    fs:  TFileStream;
    S:  string;
begin
    fs  :=  TFileStream.Create(FileName,  fmOpenread  or  fmShareDenyNone);
    try
        SetLength(S,  fs.Size);
        fs.ReadBuffer(S[1],  fs.Size);
    finally
        fs.Free;
    end;
    { the compiler stops here with: unknown identifier 'StringReplace' }
    S := StringReplace(S,  SearchString,  replaceString,  [rfReplaceAll,  rfIgnoreCase]); 
    fs  :=  TFileStream.Create(FileName,  fmCreate);
    try
        fs.WriteBuffer(S[1],  Length(S));
    finally
        fs.Free;
    end;
end;

I found out that I have to use StringChange(), instead but I don't know how to use it with my code. I don't know too much about Delphi or Inno Setup. I hope you can help me.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user3025417
  • 395
  • 1
  • 5
  • 17

1 Answers1

21

I hope this function does the job:

function FileReplaceString(const FileName, SearchString, ReplaceString: string):boolean;
var
  MyFile : TStrings;
  MyText : string;
begin
  MyFile := TStringList.Create;

  try
    result := true;

    try
      MyFile.LoadFromFile(FileName);
      MyText := MyFile.Text;

      { Only save if text has been changed. }
      if StringChangeEx(MyText, SearchString, ReplaceString, True) > 0 then
      begin;
        MyFile.Text := MyText;
        MyFile.SaveToFile(FileName);
      end;
    except
      result := false;
    end;
  finally
    MyFile.Free;
  end;
end;

Kudos to TLama for feedback.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Lars
  • 1,428
  • 1
  • 13
  • 22
  • 1
    You can use `if StringChangeEx(...) > 0 then Assign text to string list and save`. And that `OK` is not necessary. Just assign `False` to the `Result` as the very first line and assign `True` only if there won't be any exception. – TLama Nov 24 '13 at 21:33
  • @TLama, thanks for your suggestions. I modified the code that checks for changes to the file contents. Regarding the returned result; it also returns false if the file does not exist (no exception raised) so I've left unchanged. (My intention of using OK instead of result is for readability.) – Lars Nov 24 '13 at 21:52
  • 1
    IMHO, that check if the file exists should be done outside this function, before you call it (imagine, you'd call e.g. 10 functions working with the same file and in each one you'd ask if that same file exists). I know, it's the matter of taste, but you are going to raise an exception if the file opening fails for some reason (mostly access rights), so why not to raise an expcetion even if the file cannot be opened because it doesn't exist ? About that `OK`, well, I'm so tied to a "properly" written code, that I'm finding out that construction confusing. But again, it's a matter of taste :-) – TLama Nov 24 '13 at 22:02