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

如何通过TMemIniFile或TIniFile修改INI文件的节名称?

Delphi中修改INI文件节名称的实现方法

Delphi的TIniFile和TMemIniFile组件没有提供直接修改INI节名称的内置方法,但可以通过手动复制节内容、创建新节并删除旧节的方式实现需求,以下是针对两个组件的具体实现:

一、使用TIniFile实现节重命名

TIniFile直接操作磁盘文件,需要先读取旧节的所有键值对,再写入新节,最后删除旧节:

procedure RenameIniSection(const IniFile: TIniFile; const OldSection, NewSection: string);
var
  Keys: TStringList;
  I: Integer;
  Key, Value: string;
begin
  // 跳过无效操作:新旧节名相同或旧节不存在
  if (OldSection = NewSection) or not IniFile.SectionExists(OldSection) then
    Exit;

  Keys := TStringList.Create;
  try
    // 获取旧节下的所有键名
    IniFile.ReadSection(OldSection, Keys);
    // 遍历键名,将对应值写入新节
    for I := 0 to Keys.Count - 1 do
    begin
      Key := Keys[I];
      Value := IniFile.ReadString(OldSection, Key, '');
      IniFile.WriteString(NewSection, Key, Value);
    end;
    // 删除旧节
    IniFile.EraseSection(OldSection);
    // 保存更改到磁盘
    IniFile.UpdateFile;
  finally
    Keys.Free;
  end;
end;

二、使用TMemIniFile实现节重命名

TMemIniFile将INI内容加载到内存中操作,效率更高,且提供了更便捷的节内容读取方法:

procedure RenameMemIniSection(const MemIniFile: TMemIniFile; const OldSection, NewSection: string);
var
  OldSectionData: TStrings;
begin
  // 跳过无效操作
  if (OldSection = NewSection) or not MemIniFile.SectionExists(OldSection) then
    Exit;

  OldSectionData := TStringList.Create;
  try
    // 直接读取旧节的所有键值对(格式为"Key=Value")
    MemIniFile.ReadSectionValues(OldSection, OldSectionData);
    // 将键值对批量写入新节
    MemIniFile.WriteSection(NewSection, OldSectionData);
    // 删除旧节
    MemIniFile.EraseSection(OldSection);
    // 保存内存中的修改到文件
    MemIniFile.SaveToFile(MemIniFile.FileName);
  finally
    OldSectionData.Free;
  end;
end;

注意事项

  • 操作前务必检查旧节是否存在,以及新旧节名称是否一致,避免无意义的磁盘或内存操作。
  • 若处理大体积INI文件,优先使用TMemIniFile,减少磁盘IO次数提升效率。
  • 标准INI规范要求节名称唯一,若文件中存在重复节名,需额外处理冲突情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:52:13