2007. június 7., csütörtök

Merge the sections of two TIniFiles


Problem/Question/Abstract:

Imagine there are two win.ini files and I want to combine both together. Some of the common sections and keys/ values are the same in each but they differ in their data generally. How could I merge the two together to get an ini file that contains all the data from both in the right places?

Answer:

Iterate over the sections in the source file. For each section, iterate over the names. If there is a name in Source that already exists in Dest, Dest's copy will be overwritten.

{ ... }
var
  Source, Dest: TIniFile;
  SectionNames: TStrings;
  i: Integer;
begin
  SectionNames := TStringList.Create;
  try
    Source.ReadSections(SectionNames);
    for i := 0 to SectionNames.Count - 1 do
    begin
      MergeSection(Source, Dest, SectionNames[i]);
    end;
  finally
    SectionNames.Free;
  end;
end;

procedure MergeSection(Source, Dest: TIniFile; const SectionName: string);
var
  i: Integer;
  Section: TStrings;
  Name, Value: string;
begin
  Section := TStringList.Create;
  try
    Source.ReadSection(SectionName, Section);
    for i := 0 to Section.Count - 1 do
    begin
      Name := Section.Names[i];
      Value := Section.Values[Name];
      Dest.WriteString(SectionName, Name, Value);
    end;
  finally
    Section.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése