C# 动态更改 app.config 文件中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1357240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:35:14  来源:igfitidea点击:

Change the value in app.config file dynamically

c#.net

提问by Partha

I want to modify a value in appSetting section in app.config. So i wrote,

我想修改 app.config 中 appSetting 部分的值。所以我写道,

Console.WriteLine(ConfigurationManager.AppSettings["name"]);
Console.Read();
Configuration config=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
config.AppSettings.Settings["name"].Value = "raja";       
config.Save(ConfigurationSaveMode.Modified);  
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
Console.Read();

after the execution of above code, i verified the app.config whether the value of "name" element has been changed or not. but no change.

执行上述代码后,我验证了 app.config 是否已更改“name”元素的值。但没有变化。

what is the wrong with my code? or is there any other way to do this?

我的代码有什么问题?或者有没有其他方法可以做到这一点?

回答by Aleksandar Vucetic

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

它有效,只需查看 bin/Debug 文件夹,您可能正在查看项目中的 app.config 文件。

回答by Pierre-Alain Vigeant

You have to update your app.config file manually

你必须手动更新你的 app.config 文件

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// Do whatever you need, like modifying the appSettings section

// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

And then tell your application to reload any section you modified

然后告诉您的应用程序重新加载您修改的任何部分

ConfigurationManager.RefreshSection("appSettings");

回答by Adis H

This code works for me:

这段代码对我有用:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

注意:如果您使用 F5 运行它,它不会更新解决方案项“app.config”,而是更新 bin/ 文件夹中的“.exe.config”项。

回答by AviZ

Try:

尝试:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("configFilePath");
config.AppSettings.Settings.Add("configFilePath", configFilePath);
config.Save(ConfigurationSaveMode.Modified,true);
config.SaveAs(@"C:\Users\USERNAME\Documents\Visual Studio 2010\Projects\ADI2v1.4\ADI2CE2\App.config",ConfigurationSaveMode.Modified, true); 

回答by CCondron

Expanding on Adis H's example to include the null case (got bit on this one)

扩展 Adis H 的示例以包含空情况(对此有所了解)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

回答by Rahul Singh

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);