如何在安装创建的 INI 文件中添加注释

How can I add comments in INI file created by installation

我想知道是否有任何方法可以在 INI 文件中添加注释,以便用户了解设置可以具有的可能值

例如:

我当前的 INI 文件是这样的:

[Section]
Setting1=value
Setting2=Value

我想要这样

[Section]
; acceptable values for Setting1 are
; A -
; B -
Setting1=value

; acceptable values for Setting2 are
; X -
; Y -
Setting2=Value

没有 Inno Setup 函数,也没有 Windows API 来处理 INI 文件中的注释。

因此,要么您需要以编程方式创建整个 INI 文件,包括注释。或者代码只是添加注释;下面包含示例。

const
  CommentPrefix = ';';

function SetIniComment(
  FileName: string; Section: string; Key: string; Comment: string): Boolean;
var
  Lines: TArrayOfString;
  Line: string;
  InSection: string;
  I, I2, P: Integer;
begin
  Result := False;

  { load INI file lines }
  if LoadStringsFromFile(FileName, Lines) then
  begin
    Log(Format('Read %d lines', [GetArrayLength(Lines)])); 

    { iterate lines to look for the section and key }
    for I := 0 to GetArrayLength(Lines) - 1 do
    begin
      Line := Lines[I];
      { is it a start of a section? }
      if (Length(Line) > 0) and (Line[1] = '[') then
      begin
        P := Pos(']', Line);
        if P > 0 then
        begin
          InSection := Trim(Copy(Line, 2, P - 2));
        end;
      end
        else
      { are we in "our" section }
      if CompareText(InSection, Section) = 0 then
      begin
        P := Pos('=', Line);

        { is it "our" key? }
        if (P > 0) and
           (CompareText(Trim(Copy(Line, 1, P - 1)), Key) = 0) then
        begin
          { if there's already a comment on a previous line, replace it }
          if (Length(Lines[I - 1]) > 0) and
             (Lines[I - 1][1] = CommentPrefix) then
          begin
            Log(Format('Replacing existing comment on line %d', [I - 1]));
            Lines[I - 1] := CommentPrefix + ' ' + Comment;
          end
            else
          begin
            { if there's no comment yet, insert new comment line }
            Log(Format('Inserting comment to line %d', [I]));
            SetArrayLength(Lines, GetArrayLength(Lines) + 1);

            for I2 := GetArrayLength(Lines) - 1 downto I + 1 do
            begin
              Lines[I2] := Lines[I2 - 1];
            end;
            Lines[I] := CommentPrefix + ' ' + Comment;
          end;

          Log(Format('Writing %d lines', [GetArrayLength(Lines)])); 
          Result := SaveStringsToFile(FileName, Lines, False);
          break;
        end;
      end;
    end;
  end;

  if not Result then
  begin
    Log('Section/Key not found');
  end;
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  FileName: string;
begin
  if CurStep = ssPostInstall then
  begin
    FileName := ExpandConstant('{app}\my.ini');

    SetIniComment(
      FileName, 'Section', 'Setting1', 'acceptable values for Setting1 are A, B');

    SetIniComment(
      FileName, 'Section', 'Setting2', 'acceptable values for Setting1 are X, Y');
  end;
end;

尝试使用“#”前缀将行标记为注释:

[Section]
# acceptable values for Setting1 are
# A -
# B -
Setting1=value