Inno Setup Modify text file and change a specific

2019-04-17 05:56发布

问题:

I need to open a INI file and read a specific value and check if that have different change that.

But the case is my INI file doesn't have any section or key values

For example, the file contains below 2 lines only. What I need is to read the second line (it should be 16001). If it is not match then change that one.

Nexusdb@localhost
16000

Please suggest any ideas, it would be very helpful to me!

Thank you in advance.

回答1:

Your file is not an INI file. Not only it does not have sections, it does not even have keys.

You have to edit the file as a plain text file. You cannot use INI file functions.

This code will do:

function GetLastError(): LongInt; external 'GetLastError@kernel32.dll stdcall';

function SetLineInFile(FileName: string; Index: Integer; Line: string): Boolean;
var
  Lines: TArrayOfString;
  Count: Integer;
begin
  if not LoadStringsFromFile(FileName, Lines) then
  begin
    Log(Format('Error reading file "%s". %s', [FileName, SysErrorMessage(GetLastError)]));
    Result := False;
  end
    else
  begin
    Count := GetArrayLength(Lines);
    if Index >= GetArrayLength(Lines) then
    begin
      Log(Format('There''s no line %d in file "%s". There are %d lines only.', [
            Index, FileName, Count]));
      Result := False;
    end
      else
    if Lines[Index] = Line then
    begin                     
      Log(Format('Line %d in file "%s" is already "%s". Not changing.', [
            Index, FileName, Line]));
      Result := True;
    end
      else
    begin
      Log(Format('Updating line %d in file "%s" from "%s" to "%s".', [
            Index, FileName, Lines[Index], Line]));
      Lines[Index] := Line;
      if not SaveStringsToFile(FileName, Lines, False) then
      begin
        Log(Format('Error writting file "%s". %s', [
              FileName, SysErrorMessage(GetLastError)]));
        Result := False;
      end
        else
      begin
        Log(Format('File "%s" saved.', [FileName]));
        Result := True;
      end;
    end;
  end;
end;

Use it like:

SetLineInFile(ExpandConstant('{app}\Myini.ini'), 1, '16001');

(indexes are zero-based)



标签: inno-setup