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

メソッドを使用してすべてのセクションを読み取り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 に答える