以下是一个示例代码,可以循环读取ini文件中的内容:

using System.Runtime.InteropServices; //引入命名空间

class IniFile
{
    //读取ini文件中的内容
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(
        string section,
        string key,
        string def,
        StringBuilder retVal,
        int size,
        string filePath);

    //写入ini文件中的内容
    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(
        string section,
        string key,
        string val,
        string filePath);

    private string filePath; //ini文件路径

    //构造函数
    public IniFile(string filePath)
    {
        this.filePath = filePath;
    }

    //读取指定section下的所有key-value
    public Dictionary<string, string> ReadSection(string section)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        StringBuilder sb = new StringBuilder(1024); //缓冲区大小
        int len = GetPrivateProfileString(section, null, null, sb, sb.Capacity, filePath);
        string[] keys = sb.ToString().Split('\0');
        foreach (string key in keys)
        {
            if (!string.IsNullOrEmpty(key))
            {
                string val = ReadValue(section, key);
                dict.Add(key, val);
            }
        }
        return dict;
    }

    //读取指定section下的指定key的值
    public string ReadValue(string section, string key)
    {
        StringBuilder sb = new StringBuilder(1024); //缓冲区大小
        int len = GetPrivateProfileString(section, key, null, sb, sb.Capacity, filePath);
        return sb.ToString();
    }

    //写入指定section下的指定key的值
    public void WriteValue(string section, string key, string value)
    {
        WritePrivateProfileString(section, key, value, filePath);
    }
}

使用示例:

IniFile ini = new IniFile("test.ini");
Dictionary<string, string> dict = ini.ReadSection("Section1");
foreach (KeyValuePair<string, string> kvp in dict)
{
    Console.WriteLine(kvp.Key + " = " + kvp.Value);
}
``
WPF C# 循环读取ini文件下的内容

原文地址: http://www.cveoy.top/t/topic/cOyo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录