C# applicationSettings: how to update app.config?

后端 未结 4 969
滥情空心
滥情空心 2020-12-10 19:13

I am using .NET 4.0 and I would like to use the app.config file to store same parameter settings. I do the following. I use the Settings tab in the

4条回答
  •  暖寄归人
    2020-12-10 19:23

    Here's my function to update or add an entry into the app.config for "applicationSettings" section. There might be a better way, but this works for me. If anyone can suggest a better method please share it, we'll always looking for something better.

        static string APPNODE = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
        static DateTime now = DateTime.Now;
        Utilities.UpdateConfig(APPNODE, "lastQueryTime", now.ToString());
    
        static public void UpdateConfig(string section, string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
            ClientSettingsSection applicationSettingsSection = (ClientSettingsSection)config.SectionGroups["applicationSettings"].Sections[section];
            SettingElement element = applicationSettingsSection.Settings.Get(key);
    
            if (null != element)
            {
                applicationSettingsSection.Settings.Remove(element);
                element.Value.ValueXml.InnerXml = value;
                applicationSettingsSection.Settings.Add(element);
            }
            else
            {
                element = new SettingElement(key, SettingsSerializeAs.String);
                element.Value = new SettingValueElement();
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                element.Value.ValueXml = doc.CreateElement("value");
    
                element.Value.ValueXml.InnerXml = value;
                applicationSettingsSection.Settings.Add(element);
            }
    
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");            
        }
    

提交回复
热议问题