WPF C# 循环读取 INI 文件:使用 [DllImport("kernel32")] 方法
可以使用以下代码来循环读取ini文件下的内容:
using System.Runtime.InteropServices;
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 WriteValue(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.path);
}
public string ReadValue(string section, string key)
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, '', sb, 255, this.path);
return sb.ToString();
}
public List<string> ReadSection(string section)
{
List<string> result = new List<string>();
StringBuilder sb = new StringBuilder(32768);
GetPrivateProfileString(section, null, '', sb, 32768, this.path);
string[] keys = sb.ToString().Split('\0');
foreach (string key in keys)
{
if (!string.IsNullOrEmpty(key))
{
result.Add(key);
}
}
return result;
}
public Dictionary<string, string> ReadSectionValues(string section)
{
Dictionary<string, string> result = new Dictionary<string, string>();
List<string> keys = ReadSection(section);
foreach (string key in keys)
{
result.Add(key, ReadValue(section, key));
}
return result;
}
}
使用方法:
IniFile ini = new IniFile('path/to/ini/file.ini');
// 读取指定section下的所有key
List<string> keys = ini.ReadSection('写日志');
foreach (string key in keys)
{
// 读取指定section下指定key的值
string value = ini.ReadValue('写日志', key);
Console.WriteLine(key + '=' + value);
}
输出结果:
20230421103922946=.T1.PD1
原文地址: https://www.cveoy.top/t/topic/kdV4 著作权归作者所有。请勿转载和采集!