George Hovhannisian
George Hovhannisian

Reputation: 707

inno setup - Create ini key even if it exists

I need to create multiple keys with the same name, without overwriting the existing keys with that name, preferably right below or above them. For example, a key named App already exists in the ini, I need to create another key (or several) named App without overwriting the existing one. As far as I understand that's impossible to do from the [ini] section. So, how can I force create a new key even if it exists?

Upvotes: 0

Views: 353

Answers (1)

TLama
TLama

Reputation: 76713

There is no built-in function for this because what you're asking for breaks the INI file format. In INI files, within each section, every key name must be unique, which you are going to violate. But the following function might do what you want:

[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;

Call it like:

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

Upvotes: 1

Related Questions