Inno Customization Change a text file and change a specific line

I need to open an INI file and read a specific value and check if these have different changes.

But in this case, my INI file does not have any section or key values

For example, a file contains less than two lines. I need to read the second line (it should be 16001). If it does not match, change it.

Nexusdb@localhost
16000

Please suggest any ideas, this would be very helpful for me!

Thanks in advance.

0
source share
1 answer

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

You must edit the file as a regular text file. You cannot use the functions of the INI file.

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' 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 as:

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

( )

+3

Source: https://habr.com/ru/post/1651361/


All Articles