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

Delphi如何读取INI文件所有Section名称存入列表并绑定到ComboBox

获取INI文件所有Section名称的实现方法

通用手动解析逻辑

如果不想依赖第三方库或者语言内置API,可以自己逐行解析,逻辑非常简单:

  • 逐行读取INI文件内容,去除每行首尾的空格、换行符等空白字符
  • 筛选出符合[xxx]格式的行(行首为[、行尾为]且长度大于2)
  • 截取[和]中间的内容存入列表即可

示例(Python手动实现):

section_list = []
with open("test.ini", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line.startswith("[") and line.endswith("]") and len(line) > 2:
            section_name = line[1:-1].strip()
            section_list.append(section_name)
# 输出即为 ['Toronto', 'Vancouver']

不同开发语言的内置方法

Python(使用标准库configparser)

不需要安装第三方依赖,直接调用内置方法即可:

import configparser

config = configparser.ConfigParser()
config.read("test.ini", encoding="utf-8")
# 直接获取所有Section的列表
section_list = config.sections()
# 绑定到PyQt/PySide的ComboBox示例
# combo_box.addItems(section_list)

C#(调用Win32原生API)

using System.Runtime.InteropServices;

public class IniHelper
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);

    public List<string> GetAllSections(string iniFilePath)
    {
        List<string> sections = new List<string>();
        IntPtr buffer = Marshal.AllocHGlobal(1024 * 20);
        uint length = GetPrivateProfileSectionNames(buffer, 1024 * 20, iniFilePath);
        if (length > 0)
        {
            string rawStr = Marshal.PtrToStringAuto(buffer, (int)length);
            sections.AddRange(rawStr.Split('\0', StringSplitOptions.RemoveEmptyEntries));
        }
        Marshal.FreeHGlobal(buffer);
        // 绑定到WinForm/WPF ComboBox示例
        // comboBox.ItemsSource = sections;
        return sections;
    }
}

Delphi(使用VCL内置TIniFile)

uses IniFiles, Classes;

procedure TForm1.LoadSectionsToComboBox;
var
  iniFile: TIniFile;
  sectionList: TStringList;
begin
  iniFile := TIniFile.Create('test.ini');
  sectionList := TStringList.Create;
  try
    iniFile.ReadSections(sectionList);
    // 直接绑定到ComboBox
    ComboBox1.Items.Assign(sectionList);
  finally
    sectionList.Free;
    iniFile.Free;
  end;
end;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:48:00