- ///
- /// INI 文件操作类
- ///
- public class IniFileHelper {
- ///
- /// INI 配置文件路径
- ///
- private static string strIniFilePath = AppDomain.CurrentDomain.BaseDirectory + "PrintDesigner.ini";
- // 返回 0 表示失败, 非 0 为成功
- [DllImport("kernel32", CharSet = CharSet.Auto)]
- private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
- // 返回取得字符串缓冲区的长度
- [DllImport("kernel32", CharSet = CharSet.Auto)]
- private static extern long GetPrivateProfileString(string section, string key, string strDefault, StringBuilder retVal, int size, string filePath);
- [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
- public static extern int GetPrivateProfileInt(string section, string key, int nDefault, string filePath);
- public IniFileHelper() {
- }
- ///
- /// 获取 INI 配置文件中的字符串
- ///
- /// 节名
- /// 键名
- /// 默认值
- /// 结果缓冲区
- /// 结果缓冲区大小
- ///
- public static string GetIniString(string section, string key, string strDefault = "") {
- StringBuilder sb = new StringBuilder(1000);
- long liRet = GetPrivateProfileString(section, key, strDefault, sb, sb.Capacity, strIniFilePath);
- return sb.ToString();
- }
- ///
- /// 获取 INI 配置文件中的整型值
- ///
- /// 节名
- /// 键名
- /// 默认值
- ///
- public static int GetIniInt(string section, string key, int nDefault) {
- return GetPrivateProfileInt(section, key, nDefault, strIniFilePath);
- }
- ///
- /// 往 INI 配置文件写入字符串
- ///
- /// 节名
- /// 键名
- /// 要写入的字符串
- /// 成功 true, 失败 false
- public static bool WriteIniString(string section, string key, string val) {
- long liRet = WritePrivateProfileString(section, key, val, strIniFilePath);
- return (liRet != 0);
- }
- ///
- /// 往 INI 配置文件写入整型数据
- ///
- /// 节名
- /// 键名
- /// 要写入的数据
- /// 成功 true, 失败 false
- public static bool WriteIniInt(string section, string key, int val) {
- return WriteIniString(section, key, val.ToString());
- }
- }
读取:
tbUserName.Text = IniFileHelper.GetIniString("Config", "UserName");
写入:
IniFileHelper.WriteIniString("Config", "UserName", User.username);
来源: http://www.bubuko.com/infodetail-3136321.html