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

Par*_*tha 24 .net c#

我想修改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();
Run Code Online (Sandbox Code Playgroud)

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

我的代码出了什么问题?或者还有其他方法吗?

小智 51

这段代码适合我:

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

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

  • 这不起作用。在我下次重新运行应用程序之前,它仍然没有显示设置已更改。不知道发生了什么。 (2认同)

Pie*_*ant 5

您必须手动更新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);
Run Code Online (Sandbox Code Playgroud)

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

ConfigurationManager.RefreshSection("appSettings");
Run Code Online (Sandbox Code Playgroud)

  • 请注意更新最可能位于Program Files中的文件的任何安全问题.在Vista下,您需要提升权限才能写入Program Files中的文件. (4认同)

CCo*_*ron 5

在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");
Run Code Online (Sandbox Code Playgroud)


Ale*_*tic 1

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