Search code examples
delphidelphi-7ini

How to merge entries from two TINIfile instances?


Is there a way to merge entries from one TIniFile instance to another?


Solution

  • Here's a procedure which can merge two INI files together into a new output INI file:

    procedure MergeIniFiles(const FromFilename, ToFilename, OutputFilename: String;
      const Overwrite: Boolean);
    var
      IniFrom, IniTo, IniOut: TIniFile;
      Sec: TStringList;
      Val: TStringList;
      X, Y: Integer;
      S, N, V: String;
    begin
      IniFrom:= TIniFile.Create(FromFilename);
      IniTo:= TIniFile.Create(ToFilename);
      IniOut:= TIniFile.Create(OutputFilename);
      Sec:= TStringList.Create;
      Val:= TStringList.Create;
      try
        IniFrom.ReadSections(Sec);
        for X := 0 to Sec.Count-1 do begin
          S:= Sec[X];
          IniFrom.ReadSection(S, Val);
          for Y := 0 to Val.Count-1 do begin
            N:= Val[Y];
            V:= IniFrom.ReadString(S, N, '');
            IniOut.WriteString(S, N, V);
          end;
        end;
    
        IniTo.ReadSections(Sec);
        for X := 0 to Sec.Count-1 do begin
          S:= Sec[X];
          IniTo.ReadSection(S, Val);
          for Y := 0 to Val.Count-1 do begin
            N:= Val[Y];
            V:= IniTo.ReadString(S, N, '');
            if Overwrite then begin
              IniOut.WriteString(S, N, V);
            end else begin
              if not IniOut.ValueExists(S, N) then
                IniOut.WriteString(S, N, V);
            end;
          end;
        end;
      finally
        Val.Free;
        Sec.Free;
        IniOut.Free;
        IniTo.Free;
        IniFrom.Free;
      end;
    end;