【问题标题】:Updating .config file with data from the user使用来自用户的数据更新 .config 文件
【发布时间】:2014-08-13 15:30:21
【问题描述】:

我正在尝试将一些设置保存到我的配置文件的 appSettings 部分,以便我可以使用这些数据来执行程序的进程。单击按钮时,我希望将来自用户的数据保存在配置文件中。我使用的代码是:

private void button1_Click(object sender, EventArgs e)
{

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings["key1"].Value = "value1";
            config.AppSettings.Settings["key2"].Value = "value2";

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

}

在执行代码之前,我的 app.config 文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="roshane" value=""/>
    <add key="email" value=""/>
    <add key="super" value=""/>
    <add key="phone" value=""/>
  </appSettings>
  <connectionStrings>
    <add name="AutoReportEmailerConnectionString"
        connectionString="Data Source=roshane\sqlexpress;Initial Catalog=ICR_v5.0;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
</configuration>

代码执行后programName.exe.config文件与app.config文件相同。为什么没有将这些值添加到 programName.exe.config 文件中,我是否遗漏了什么?

【问题讨论】:

  • 边界重复。建议您吸收this answer中的信息并重新考虑您的问题。
  • 在你使用“key1”和“key2”的地方你应该使用“roshane”或“email”.....
  • 您要添加值还是修改现有值?

标签: c# app-config appsettings


【解决方案1】:

config.Save(ConfigurationSaveMode.Modified) 仅在您修改现有键时起作用,换句话说,如果您需要将键值实际添加到 Web 配置中,只需调用 config.Save()无参数

【讨论】:

    【解决方案2】:

    如果要在配置文件中添加新的 Key,需要先在 Settings 集合中添加:

    config.AppSettings.Settings.Add("Key", "Value");
    

    然后调用Save方法。

    【讨论】:

    • 是的,我知道它的标题使用更新词,但最后 OP 说添加了所以你可能是对的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多