2

我有一个 INI 文件,其中存储了一些用于设置的整数。部分名称存储如下:

[ColorScheme_2]
name=Dark Purple Gradient
BackgroundColor=224
BackgroundBottom=2
BackgroundTop=25
...

[ColorScheme_3]
name=Retro
BackgroundColor=5
BackgroundBottom=21
BackgroundTop=8
...

我需要找出一种方法来创建新的部分,从最高的部分编号增加配色方案编号 +1。我有一个组合框,列出了当前的颜色方案名称,因此当用户保存到 INI 文件时,现有方案将被覆盖。如何检查 ComboBox 文本以查看它是否是现有部分,如果不是,则创建一个具有递增名称的新部分?(即来自上面的示例代码,ColorScheme_2并且ColorScheme_3已经存在,因此下一部分要创建ColorScheme_4)。

4

2 回答 2

8

您可以通过 using 方法读取所有部分ReadSections,然后迭代返回的字符串列表并解析其中的每个项目以存储找到的最高索引值:

uses
  IniFiles;

function GetMaxSectionIndex(const AFileName: string): Integer;
var
  S: string;
  I: Integer;
  Index: Integer;
  IniFile: TIniFile;
  Sections: TStringList;
const
  ColorScheme = 'ColorScheme_';
begin
  Result := 0;
  IniFile := TIniFile.Create(AFileName);
  try
    Sections := TStringList.Create;
    try
      IniFile.ReadSections(Sections);
      for I := 0 to Sections.Count - 1 do
      begin
        S := Sections[I];
        if Pos(ColorScheme, S) = 1 then
        begin
          Delete(S, 1, Length(ColorScheme));
          if TryStrToInt(S, Index) then
            if Index > Result then
              Result := Index;
        end;
      end;
    finally
      Sections.Free;
    end;
  finally
    IniFile.Free;
  end;
end;

以及用法:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(IntToStr(GetMaxSectionIndex('d:\Config.ini')));
end;
于 2013-03-03T18:17:10.367 回答
4

如何检查 ComboBox 文本以查看它是否是现有部分,如果不是,则创建一个具有递增名称的新部分?

像这样:

const
  cPrefix = 'ColorScheme_';
var
  Ini: TIniFile;
  Sections: TStringList;
  SectionName: String;
  I, Number, MaxNumber: Integer;
begin
  Ini := TIniFile.Create('myfile.ini')
  try
    SectionName := ComboBox1.Text;
    Sections := TStringList.Create;
    try
      Ini.ReadSections(Sections);
      Sections.CaseSensitive := False;
      if Sections.IndexOf(SectionName) = -1 then
      begin
        MaxNumber := 0;
        for I := 0 to Sections.Count-1 do
        begin
          if StartsText(cPrefix, Sections[I]) then
          begin
            if TryStrToInt(Copy(Sections[I], Length(cPrefix)+1, MaxInt), Number) then
            begin
              if Number > MaxNumber then
                MaxNumber := Number;
            end;
          end;
        end;
        SectionName := Format('%s%d', [cPrefix, MaxNumber+1]);
      end;
    finally
      Sections.Free;
    end;
    // use SectionName as needed...
  finally
    Ini.Free;
  end;
end;
于 2013-03-03T20:07:42.110 回答