以下是 WPF C# 循环读取 INI 文件内容的示例代码:

  1. 首先,需要引用 System.IOSystem.Runtime.InteropServices 命名空间。
using System.IO;
using System.Runtime.InteropServices;
  1. 声明 GetPrivateProfileString 函数,用于读取 INI 文件中的内容。
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  1. 编写读取 INI 文件的方法。
private string ReadIniFile(string section, string key, string filePath)
{
    StringBuilder sb = new StringBuilder(255);
    int i = GetPrivateProfileString(section, key, "", sb, 255, filePath);
    return sb.ToString();
}
  1. 在需要读取 INI 文件的地方调用该方法。
string value = ReadIniFile("SectionName", "KeyName", "FilePath.ini");
  1. 如果需要循环读取 INI 文件的内容,可以使用以下代码示例:
private void ReadIniFileLoop(string filePath)
{
    string[] sections = File.ReadAllLines(filePath)
        .Where(line => line.StartsWith("[") && line.EndsWith("]"))
        .Select(line => line.Substring(1, line.Length - 2))
        .ToArray();

    foreach (string section in sections)
    {
        string[] keys = File.ReadAllLines(filePath)
            .Where(line => line.StartsWith(section + "="))
            .Select(line => line.Substring(section.Length + 1))
            .ToArray();

        foreach (string key in keys)
        {
            string value = ReadIniFile(section, key, filePath);
            // 处理读取到的内容
        }
    }
}

以上是 WPF C# 循环读取 INI 文件内容的示例代码。

WPF C# 循环读取 INI 文件内容 - 代码示例

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

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