Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

pascalscript - Replace a text in a file with Inno Setup

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...