C#读写,删除配置文件(Config.ini)

2019-08-27 更新 添加删除功能

核心代码如下

        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filepath);
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// <summary>
        /// 读配置文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <param name="size"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static String ReadIni(string section, string key, string def, int size, string filepath)
        {
            StringBuilder sb = new StringBuilder(4096);
            GetPrivateProfileString(section, key, def, sb, size, filepath);
            return sb.ToString();
        }
        /// <summary>
        /// 写入数据到配置文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static long WriteIni(string section, string key, string val, string filepath)
        {
            return WritePrivateProfileString(section, key, val, filepath);
        }
        // 删除ini文件下所有段落
        public void ClearAllSection(string filepath)
        {
            WriteIni(null,null,null,filepath);
        }
        //删除ini文件下personal段落下的所有键
        public void ClearSection(string Section,string filepath)
        {
            WriteIni(Section,null,null,filepath);
        }
        //转载请保留原创地址http://www.luofenming.com/show.aspx?id=ART2018032800001

以下是方法调用

 //读取配置文件 如果没有则 192.168.1.2 为默认值
readIni("IPSet", "IP", "192.168.1.2", 255, @"d:\config.ini");
//写入config.ini
writeIni("IPSet", "IP", "192.168.1.2", @"d:\config.ini");

评论