INI文件读写

如有不明白的地方欢迎加QQ群 14670545 探讨
public class IniHelp
    {
        /// 
        /// INI文件路径(私有变量)
        /// 
        private string _iniPath;

        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        /// 
        /// 设置INI文件路径
        /// 
        /// 
        public void setIni(string iniPath)
        {
            _iniPath = iniPath;
        }

        /// 
        /// 写INI文件
        /// 
        /// 配置节
        /// 键名
        /// 键值 
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this._iniPath);
        }

        /// 
        /// 读取INI文件指定 
        /// 
        /// 配置节
        /// 键名
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this._iniPath);
            return temp.ToString();
        }
    }

写入举例:

protected void Button_Click(object sender, EventArgs e)
        {
            string iniPath = Server.MapPath("./db.ini");

            if (!File.Exists(iniPath))
                File.Create(iniPath);

            inihelp.setIni(iniPath);
            inihelp.IniWriteValue("dbhelp", "server", ".");
            inihelp.IniWriteValue("dbhelp", "user", "sa");
            inihelp.IniWriteValue("dbhelp", "pwd", "123");
        }

没有就创建db.ini,此时文件里面的内容如下:

[dbhelp]
server=.
user=sa
pwd=123

读取举例:

 string iniPath = Server.MapPath("./db.ini");
                if (File.Exists(iniPath))
                {
                    inihelp.setIni(iniPath);
                    Response.Write(inihelp.IniReadValue("dbhelp", "user")); //读配置
                }


你可能感兴趣的:(C#)