using System.Runtime.InteropServices; using System.Text; namespace EC.Utils.Storage { public class IniFileHelper { private string FileName { get; set; } [DllImport("kernel32.dll")] private static extern int GetPrivateProfileInt( string lpAppName, string lpKeyName, int nDefault, string lpFileName ); [DllImport("kernel32.dll")] private static extern int GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName ); [DllImport("kernel32.dll")] private static extern int WritePrivateProfileString( string lpAppName, string lpKeyName, string lpString, string lpFileName ); /// /// 构造函数 /// public IniFileHelper() { } /// /// 构造函数 /// /// Ini文件路径 public IniFileHelper(string fileName) { this.FileName = fileName; } /// /// 读取指定 节-键 的值 /// /// /// /// public string IniReadValue(string section, string name) { StringBuilder strSb = new StringBuilder(256); GetPrivateProfileString(section, name, "", strSb, 256, this.FileName); return strSb.ToString(); } /// /// 写入指定值,如果不存在 节-键,则会自动创建 /// /// /// /// public void IniWriteValue(string section, string name, string value) { WritePrivateProfileString(section, name, value, this.FileName); } /// /// [扩展]读取string字符串 /// /// 节 /// 键 /// 默认值 /// public string ReadString(string section, string name, string def) { StringBuilder vRetSb = new StringBuilder(2048); GetPrivateProfileString(section, name, def, vRetSb, 2048, this.FileName); return vRetSb.ToString(); } /// /// [扩展]写入String字符串,如果不存在 节-键,则会自动创建 /// /// 节 /// 键 /// 写入值 public void WriteString(string section, string name, string strVal) { WritePrivateProfileString(section, name, strVal, this.FileName); } /// /// [扩展]读Int数值 /// /// 节 /// 键 /// 默认值 /// public int ReadInt(string section, string name, int def) { return GetPrivateProfileInt(section, name, def, this.FileName); } /// /// [扩展]写入Int数值,如果不存在 节-键,则会自动创建 /// /// 节 /// 键 /// 写入值 public void WriteInt(string section, string name, int intVal) { WritePrivateProfileString(section, name, intVal.ToString(), this.FileName); } /// /// 删除指定的 节 /// /// public void DeleteSection(string section) { WritePrivateProfileString(section, null, null, this.FileName); } /// /// 删除全部 节 /// public void DeleteAllSection() { WritePrivateProfileString(null, null, null, this.FileName); } } }