public class INIHelper { /// <summary> /// 写入指定配置文件、指定节、指定键的值 /// </summary> /// <param name="section">节名</param> /// <param name="key">键名</param> /// <param name="retVal">返回值</param> /// <param name="filePath">配置文件路径</param> /// <returns>写入的数据字节长度</returns> [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")] private static extern long WritePrivateProfileString(string section, string key, string retVal, string filePath); /// <summary> /// 读取指定配置文件、指定节、指定键的值 /// </summary> /// <param name="section">节点名</param> /// <param name="key">键名</param> /// <param name="def">默认值</param> /// <param name="retVal">返回值</param> /// <param name="size">缓冲区长度</param> /// <param name="filePath">配置文件路径</param> /// <returns>读取的数据字节长度</returns> [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// <summary> /// 读取指定配置文件、指定节的所有键值对 /// </summary> /// <param name="section">节名</param> /// <param name="retVal">返回值(所有键和值)</param> /// <param name="size">缓冲区长度</param> /// <param name="filePath">配置文件路径</param> /// <returns>读取的数据字节长度</returns> [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSection")] private static extern int GetPrivateProfileSection(string section, byte[] retVal, int size, string filePath); /// <summary> /// 读取指定配置文件的所有节名 /// </summary> /// <param name="retVal">返回值(所有节名)</param> /// <param name="size">缓冲区长度</param> /// <param name="filePath">配置文件路径</param> /// <returns>读取的数据字节长度</returns> [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames")] private static extern int GetPrivateProfileSectionNames( byte[] retVal, int size, string filePath); public static void WriteValue(string iniFilePath, string section, string key, string value) { WritePrivateProfileString(section, key, value, iniFilePath); } public static string ReadValue(string iniFilePath, string section, string key) { StringBuilder res = new StringBuilder(255); var len = GetPrivateProfileString(section, key, "", res, 255, iniFilePath); return res.ToString(); } public static Dictionary<string, string> ReadSection(string iniFilePath, string section) { Dictionary<string, string> res = new Dictionary<string, string>(); byte[] buffer = new byte[32768]; var len = GetPrivateProfileSection(section, buffer, buffer.GetUpperBound(0), iniFilePath); var value = System.Text.Encoding.GetEncoding("GB2312").GetString(buffer, 0, len); //