INI文件是以键值对的形式存储的。由节、键、值组成。
节
[section]
参数1(键=值)
name1=value1
参数2(键=值)
name2=value2
······
public class INIHelper
{
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string appName,string keyName,string defaultValue,StringBuilder result,int nSize,string fileName);
[DllImport("kernel32")]
private static extern int WritePrivateProfileString(string appName, string keyName, string strWrite, string fileName);
[DllImport("kernel32")]
private static extern int GetPrivateProfileStringA(string appName, string keyName, string defaultValue, Byte[] result, int nSize, string fileName);
//读取值
public static string Read(string section,string key,string def,string filePath)
{
StringBuilder strBuil = new StringBuilder(200);
GetPrivateProfileString(section, key, def, strBuil, 200, filePath);
return strBuil.ToString();
}
//写入值
public static int Write(string section, string key, string value, string filePath)
{
return WritePrivateProfileString(section, key, value, filePath);
}
//获取所有的键
public static List<string> ReadAllKeys(string section,string filePath)
{
List<string> listResult = new List<string>();
Byte[] buf = new Byte[65536];
int len=GetPrivateProfileStringA(section, null, null, buf, buf.Length, filePath);
int j = 0;
for (int i = 0; i < len; i++)
{
if (buf[i] == 0)
{
listResult.Add(Encoding.Default.GetString(buf, j, i - j));
j = i + 1;
}
}
return listResult;
}
//获取所有的节点
public static List<string> ReadAllSections(string filePath)
{
List<string> listResult = new List<string>();
Byte[] buf = new Byte[65536];
int len = GetPrivateProfileStringA(null, null, null, buf, buf.Length, filePath);
int j = 0;
for (int i = 0; i < len; i++)
{
if (buf[i] == 0)
{
listResult.Add(Encoding.Default.GetString(buf, j, i - j));
j = i + 1;
}
}
return listResult;
}
}