Winfrom 开发时,有时会将一些系统某个设置保存到Ini 类型的文件中.下面提供操作Ini 文件的代码:
public static class IniFiles { [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 static string FilePath; /// <summary> /// 写入Ini文件 /// </summary> /// <param name="section">项目名称(如 [TypeName] )</param> /// <param name="key">键</param> /// <param name="value">值</param> public static void IniWriteValue(string section, string key, string value) { WritePrivateProfileString(section, key, value, FilePath); } /// <summary> /// 读出Ini文件 /// </summary> /// <param name="section">项目名称(如 [TypeName] )</param> /// <param name="key">键</param> public static string IniReadValue(string section, string key) { StringBuilder temp = new StringBuilder(500); int i = GetPrivateProfileString(section, key, "", temp, 500, FilePath); return temp.ToString(); } /// <summary> /// 验证文件是否存在 /// </summary> /// <returns>布尔值</returns> public static bool ExistIniFile() { return File.Exists(FilePath); } }