c# ini文件操作

代码:

class Config
    {
        /// <summary>
        /// 存储的ini文件名,在APP同一级目录下
        /// </summary>
        private static string IniFileName = ".\\Config.ini";

        /// <summary>
        /// DLL写ini
        /// </summary>
        /// <param name="section">要写入的段落名</param>
        /// <param name="key">要写入的键,如果该key存在则覆盖写入</param>
        /// <param name="val">key所对应的值</param>
        /// <param name="filePath">INI文件的完整路径和文件名</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// DLL读取ini
        /// </summary>
        /// <param name="section">要读取的段落名</param>
        /// <param name="key">要读取的键</param>
        /// <param name="defVal">读取异常的情况下的缺省值</param>
        /// <param name="retVal">key所对应的值,如果该key不存在则返回空值</param>
        /// <param name="size">值允许的大小</param>
        /// <param name="filePath">INI文件的完整路径和文件名</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, System.Text.StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="Section">项目名称(如 [TypeName] )</param>
        /// <param name="Key">键</param>
        /// <param name="Value">值</param>
        public static long WriteValue(string Section, string Key, string Value)
        {
            return WritePrivateProfileString(Section, Key, Value, IniFileName);
        }

        /// <summary>
        /// 读出INI文件
        /// </summary>
        /// <param name="Section">项目名称(如 [TypeName] )</param>
        /// <param name="Key">键</param>
        public static string ReadValue(string Section, string Key, string Default)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, Key, Default, temp, 500, IniFileName);
            if (Default.Equals(temp.ToString()))
            {
                //证明配置文件中没有该项,这时候将默认值写入
                WriteValue(Section, Key, Default); 
            }
            return temp.ToString();
        }


    }


你可能感兴趣的:(c# ini文件操作)