You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi中TIniFile如何处理无键值对的INI文件内容?

Delphi处理INI文件中的无键值项

TIniFile类是基于标准INI格式设计的,仅支持键=值形式的条目,所以它的内置方法(包括ReadSectionValues)确实会忽略没有键的纯文本行。如果不想添加虚拟键,你可以手动解析INI文件来提取这些无键内容,示例代码如下:

function GetSectionValuesWithoutKeys(const IniFileName, SectionName: string): TStringList;
var
  SL: TStringList;
  i: Integer;
  InTargetSection: Boolean;
begin
  Result := TStringList.Create;
  SL := TStringList.Create;
  try
    SL.LoadFromFile(IniFileName);
    InTargetSection := False;
    for i := 0 to SL.Count - 1 do
    begin
      // 定位目标段
      if Trim(SL[i]) = '[' + SectionName + ']' then
      begin
        InTargetSection := True;
        Continue;
      end;
      // 遇到新的段,停止读取
      if InTargetSection and (Pos('[', SL[i]) = 1) then
        Break;
      // 收集目标段内的非空行
      if InTargetSection and (Trim(SL[i]) <> '') then
        Result.Add(Trim(SL[i]));
    end;
  finally
    SL.Free;
  end;
end;

// 使用示例
var
  Physicians: TStringList;
begin
  Physicians := GetSectionValuesWithoutKeys('yourfile.ini', 'physicians');
  try
    // 处理Physicians列表中的内容,比如遍历输出
    for var Item in Physicians do
      ShowMessage(Item);
  finally
    Physicians.Free;
  end;
end;

这个方法直接读取整个INI文件内容,通过字符串匹配定位到目标段,然后收集该段内的所有非空行,直到遇到下一个段标记为止。

如果使用较新版本的Delphi(如Delphi 10.4+),也可以尝试用TMemIniFile,但它同样遵循标准INI格式规范,仍需手动处理无键行,核心逻辑和上述方法一致。

内容的提问来源于stack exchange,提问作者stevenvh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:10:02