inno setup - 创建 ini 密钥,即使它存在

inno setup - Create ini key even if it exists

我需要创建多个具有相同名称的密钥,而不用该名称覆盖现有密钥,最好是在它们的正下方或上方。例如,一个名为 App 的密钥已经存在于 ini 中,我需要创建另一个(或多个)名为 App 的密钥而不覆盖现有密钥。据我了解,从 [ini] 部分不可能做到这一点。那么,即使它存在,我如何强制创建一个新密钥?

没有内置函数,因为您要求的会破坏 INI 文件格式。在 INI 文件中,在每个部分中,每个键名都必须是唯一的,您将违反这一点。但是下面的函数可能会做你想做的事:

[Code]
procedure AppendKey(const FileName, Section, KeyName, KeyValue: string);
var
  S: string;
  I: Integer;
  CurLine: string;
  LineIdx: Integer;
  SnFound: Boolean;
  Strings: TStringList;
begin
  Strings := TStringList.Create;
  try
    S := Format('[%s]', [Section]);

    Strings.LoadFromFile(FileName);
    SnFound := False;
    LineIdx := Strings.Count;

    for I := Strings.Count - 1 downto 0 do
    begin
      CurLine := Trim(Strings[I]);
      // if the iterated line is a section, then...
      if (Length(CurLine) > 2) and (CurLine[1] = '[') and (CurLine[Length(CurLine)] = ']') then
      begin
        // if the iterated line is the section we are looking for, then...
        if CompareText(S, CurLine) = 0 then
        begin
          SnFound := True;
          Break;
        end;
      end
      else
        if CurLine = '' then
          LineIdx := I;
    end;

    if not SnFound then
    begin
      Strings.Add(S);
      Strings.Add(Format('%s=%s', [KeyName, KeyValue]));
    end
    else
      Strings.Insert(LineIdx, Format('%s=%s', [KeyName, KeyValue]));

    Strings.SaveToFile(FileName);
  finally
    Strings.Free;
  end;
end;

这样称呼它:

AppendKey('C:\File.ini', 'Section', 'KeyName', 'KeyValue');