using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; namespace LSFileClient { public static class IniUtil { /// /// 写入INI文件 /// /// 节点名称[如[TypeName]] /// 键 /// 值 /// 文件路径 /// [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filepath); /// /// 读取INI文件 /// /// 节点名称 /// 键 /// 值 /// stringbulider对象 /// 字节大小 /// 文件路径 /// [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath); /// /// 说明:通过Key获取Value值 /// 创建人:龚宇超 /// 创建日期:2017-07-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 键 /// public static string ReadFileConfig(string key) { string value = string.Empty; try { //判读INI文件是否存在 string filePath = Application.StartupPath + "/MenuConfig.ini"; if (File.Exists(filePath)) { StringBuilder temp = new StringBuilder(1024); string fileName = Path.GetFileNameWithoutExtension(filePath); GetPrivateProfileString(fileName, key, "", temp, 1024, filePath); return temp + ""; } } catch (Exception) { } return value; } /// /// 说明:通过Key获取Value值 /// 创建人:龚宇超 /// 创建日期:2017-07-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 键 /// public static string Read(string iniPath, string key) { string value = string.Empty; try { //判读INI文件是否存在 string filePath = iniPath; if (File.Exists(filePath)) { StringBuilder temp = new StringBuilder(1024); string fileName = Path.GetFileNameWithoutExtension(filePath); GetPrivateProfileString(fileName, key, "", temp, 1024, filePath); return temp + ""; } } catch (Exception) { } return value; } /// /// 说明:写入Ini文件(以键值对的形式存放) /// 创建人:龚宇超 /// 创建日期:2017-07-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 键 /// 值 /// public static void WriteFileConfig(string key, string value) { try { //根据INI文件名设置要写入INI文件的节点名称 //此处的节点名称完全可以根据实际需要进行配置 string filePath = Application.StartupPath + "/MenuConfig.ini"; if (!File.Exists(filePath)) { File.Create(filePath); } string fileName = Path.GetFileNameWithoutExtension(filePath); WritePrivateProfileString(fileName, key, value, filePath); } catch (Exception ex) { } } } }