C# 操作.ini配置文件

之前写了一个项目是把MFC工程转为.Net下,MFC里面操作.ini配置文件有已有的方法,在不想改变配置文件格式的情况下,要写个C#操作.ini配置文件的方法。

如下:


所用字段:

        // <Section, <key, value>>
        private Dictionary<string, Dictionary<string, string>> configSections = new Dictionary<string, Dictionary<string, string>>();
        // <Key, Value>
        private Dictionary<string, string> configData = new Dictionary<string, string>();
        // 配置文件名
        private string fullFileName = string.Empty;

从本地加载:

        /// <summary>
        /// 从本地加载配置文件
        /// </summary>
        /// <param name="_fileName">配置文件名</param>
        public CCSharspOperateINI(string _fileName)
        {
            configData = new Dictionary<string, string>();
            configSections = new Dictionary<string, Dictionary<string, string>>();
            fullFileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + _fileName;

            bool hasCfgFile = File.Exists(fullFileName);
            if (!hasCfgFile)
            {
                File.Create(fullFileName);
            }

            using (StreamReader reader = new StreamReader(fullFileName, Encoding.GetEncoding("GB2312")))
            {
                string line = string.Empty;
                int indx = 0;
                bool bNewSection = false;

                while ((line = reader.ReadLine()) != null)
                {
                    if (line.StartsWith("["))
                    {
                        if (!configSections.ContainsKey(line.Trim()))
                        {
                            configData = new Dictionary<string, string>();
                            configSections.Add(line.Trim(), configData);
                            bNewSection = true;
                        }
                    }
                    else
                    {
                        if (bNewSection)
                        {
                            if (line.StartsWith(";") || string.IsNullOrEmpty(line.Trim()))
                            {
                                configData.Add(";" + indx++, line);
                            }
                            else
                            {
                                string[] key_value = line.Trim().Split('=');
                                if (key_value.Length >= 2)
                                {
                                    if (!configData.ContainsKey(key_value[0]))
                                    {
                                        configData.Add(key_value[0], key_value[1]);
                                    }
                                }
                                else
                                {
                                    configData.Add(";" + indx++, line);
                                }
                            }
                        }
                    }
                }
            }
        }

读取某个字段的值:

        /// <summary>
        /// 读取配置文件中某个section下某个key的值
        /// </summary>
        /// <param name="sectionName">section名</param>
        /// <param name="key">key</param>
        /// <returns></returns>
        public string GetConfigValue(string sectionName, string key)
        {
            if (null == configSections)
            { return string.Empty; }
            if (configSections.Count <= 0)
            { return string.Empty; }
            if (configSections.ContainsKey(sectionName))
            {
                if (configSections[sectionName].Count <= 0)
                { return string.Empty; }
                else if (configSections[sectionName].ContainsKey(key))
                { return configSections[sectionName][key].ToString().Trim(); }
                else
                { return string.Empty; }
            }
            else
            { return string.Empty; }
        }

设置某个字段的值:

        /// <summary>
        /// 设置某个section下某个key的值
        /// </summary>
        /// <param name="sectionName">section名</param>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public void SetConfigValue(string sectionName, string key, string value)
        {
            if (null == configSections)
            { return; }
            if (!configSections.ContainsKey(sectionName))
            {
                configSections.Add(sectionName, new Dictionary<string, string>());
            }

            if (configSections[sectionName].ContainsKey(key))
            {
                configSections[sectionName][key] = value;
            }
            else
            {
                configSections[sectionName].Add(key, value);
            }
        }


保存到本地:
        /// <summary>
        /// 保存配置文件
        /// </summary>
        public void SaveConfigData()
        {
            if (null == configSections)
            { return; }

            using (StreamWriter writer = new StreamWriter(fullFileName, false, Encoding.GetEncoding("GB2312")))
            {
                IDictionaryEnumerator enuSection = configSections.GetEnumerator();
                while (enuSection.MoveNext())
                {
                    writer.WriteLine(enuSection.Key.ToString());
                    Dictionary<string, string> tmp = enuSection.Value as Dictionary<string, string>;

                    if (null != tmp)
                    {
                        IDictionaryEnumerator enu = tmp.GetEnumerator();
                        while (enu.MoveNext())
                        {
                            if (enu.Key.ToString().StartsWith(";"))
                                writer.WriteLine(enu.Value);
                            else
                                writer.WriteLine(enu.Key + "=" + enu.Value);
                        }
                    }
                }
            }
        }

注: Set之后都要保存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值