以下这段代码只能读section下的第一行修改可以读取section的所有行using SystemRuntimeInteropServices;using SystemText;public class IniFile private string path; DllImportkernel32 private static extern long WritePrivatePr
修改后的代码:
using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic;
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(32768);
int i = GetPrivateProfileString(section, null, "", temp, 32768, this.path);
string[] sections = temp.ToString().Split('\0');
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; System.Console.WriteLine("Key: {0}, Value: {1}", key, value); }
//读取Section2的所有行
List
原文地址: https://www.cveoy.top/t/topic/cO9I 著作权归作者所有。请勿转载和采集!