Inno Setup 修改文本文件并更改特定行

kAs*_*sdh 1 inno-setup

我需要打开一个 INI 文件并读取特定值并检查是否有不同的更改。

但情况是我的 INI 文件没有任何部分或键值

例如,该文件仅包含以下 2 行。我需要的是读取第二行(应该是16001)。如果不匹配,则更改该匹配。

Nexusdb@localhost
16000
Run Code Online (Sandbox Code Playgroud)

请提出任何想法,这对我非常有帮助!

先感谢您。

Mar*_*ryl 5

您的文件不是 INI 文件。它不仅没有部分,甚至没有钥匙。

您必须将该文件编辑为纯文本文件。您不能使用 INI 文件函数。

这段代码将执行以下操作:

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;
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

SetLineInFile(ExpandConstant('{app}\Myini.ini'), 1, '16001');
Run Code Online (Sandbox Code Playgroud)

(索引从零开始)