Winfrom修改AppConfig之坑

142 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 Winfrom的系统AppConfig大多数情况下,我们都是用来读取一些简单的配置,如时间参数,ip端口等,但是有时候我 们可能会遇到存取一两个变量,这样的情况下,我们不会单独建一个独立的配置文件,也不会使用ini格配置文件,可能为了方便和简单 顺手直接用一下系统自带的appconfig。但是 appconfig读取容易 修改可是很坑的 

使用系统只带的方法,可能不会永久保存修改(具体问题请参考C#之app.config、exe.config和vshost.exe.config作用区别)

这种情况下 我们就只能采用原始的xml文件的读写方式去获取和设置值了,这样就可以永久的保存我们需要修改的值。

具体操作方法如下: 我们直接获取xml文件中指定的xnode节点,然后进一步修改

    public sealed class AppConfigHelper
    {

        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        public static string GetValue(string key)
        {
            ////try
            ////{
            ////    //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            ////    // return  config.AppSettings.Settings[key].Value;
            ////    return ConfigurationManager.AppSettings[key].ToString().Trim() ?? String.Empty;
            ////}
            ////catch
            ////{

            ////    return string.Empty;
            ////}

            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

                var xNode = xDoc.SelectSingleNode("//appSettings");

                var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");

                if (xElem != null)
                {
                    return xElem.Attributes["value"].Value;
                }
                return string.Empty;
            }
            catch (Exception)
            {

                return string.Empty;
            }

           
        }


        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
                var xNode = xDoc.SelectSingleNode("//appSettings");
                var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
                if (xElem != null) xElem.SetAttribute("value", value);
                else
                {
                    var xNewElem = xDoc.CreateElement("add");
                    xNewElem.SetAttribute("key", key);
                    xNewElem.SetAttribute("value", value);
                    xNode.AppendChild(xNewElem);
                }
                xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
            catch (Exception)
            {

            }

            ////try
            ////{
            ////    ConfigurationManager.AppSettings.Set(key, value);
            ////    //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            ////    //ConfigurationManager.AppSettings.Set(key, value);
            ////    //config.AppSettings.Settings[key].Value = value;
            ////    //config.SaveAs("App.config");
            ////}
            ////catch(Exception ex)
            ////{
            ////    Log.LogRecorder.AddEventRec(ex.Message);
            ////}

        }
    }

注释中的代码就是系统自带方式读取和写入,这种方式在应用程序重启后,会丢失掉已经修改后appconfig中的值,所以存在一定的特殊性。