C# WPF 使用循环读取 INI 文件内容的示例
以下是使用 C# 循环读取 INI 文件的示例代码:
using System.Runtime.InteropServices;
using System.Text;
public class IniFile
{
private string path;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal, int size, string filePath);
public IniFile(string INIPath)
{
path = INIPath;
}
public void Write(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.path);
}
public string Read(string section, string key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
return temp.ToString();
}
public List<string> ReadSection(string section)
{
List<string> values = new List<string>();
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(section, null, "", temp, 255, this.path);
string[] sections = temp.ToString().Split('�');
foreach (string s in sections)
{
if (!string.IsNullOrEmpty(s))
{
values.Add(s);
}
}
return values;
}
public Dictionary<string, string> ReadSectionValues(string section)
{
Dictionary<string, string> values = new Dictionary<string, string>();
List<string> keys = ReadSection(section);
foreach (string key in keys)
{
string value = Read(section, key);
values.Add(key, value);
}
return values;
}
}
//使用示例
IniFile ini = new IniFile("test.ini");
//写入数据
ini.Write("Section1", "Key1", "Value1");
ini.Write("Section1", "Key2", "Value2");
ini.Write("Section2", "Key3", "Value3");
//读取数据
string value1 = ini.Read("Section1", "Key1");
string value2 = ini.Read("Section1", "Key2");
string value3 = ini.Read("Section2", "Key3");
//循环读取Section1的所有键值对
Dictionary<string, string> section1Values = ini.ReadSectionValues("Section1");
foreach (KeyValuePair<string, string> kvp in section1Values)
{
string key = kvp.Key;
string value = kvp.Value;
}
本文示例代码展示了如何使用 C# 循环读取 INI 文件内容,并提供了写入、读取以及读取特定节的所有键值对等操作。代码示例简洁易懂,适合 WPF 开发者参考学习。
原文地址: https://www.cveoy.top/t/topic/kd2z 著作权归作者所有。请勿转载和采集!