C# WPF 使用 [DllImport('kernel32')] 读取 INI 文件内容
可以使用以下代码循环读取ini文件下的内容:
using System.Runtime.InteropServices;
using System.Text;
public static class IniFileHelper
{
[DllImport('kernel32')]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public static string ReadIniFile(string filePath, string section, string key)
{
StringBuilder sb = new StringBuilder(255);
int result = GetPrivateProfileString(section, key, '', sb, 255, filePath);
return sb.ToString();
}
public static List<string> ReadIniFileSection(string filePath, string section)
{
List<string> values = new List<string>();
StringBuilder sb = new StringBuilder(32768);
int result = GetPrivateProfileString(section, null, null, sb, 32768, filePath);
string[] lines = sb.ToString().Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (!line.StartsWith(';') && !line.StartsWith('#'))
{
int index = line.IndexOf('=');
if (index > 0)
{
string key = line.Substring(0, index);
string value = line.Substring(index + 1);
values.Add(value);
}
}
}
return values;
}
}
使用方法:
string filePath = 'your ini file path';
string section = '写日志';
string key = '20230421103922946';
string value = IniFileHelper.ReadIniFile(filePath, section, key);
List<string> values = IniFileHelper.ReadIniFileSection(filePath, section);
foreach(string value in values)
{
// do something with value
}
原文地址: https://www.cveoy.top/t/topic/kdYK 著作权归作者所有。请勿转载和采集!