Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用来自用户的数据更新.config文件_C#_App Config_Appsettings - Fatal编程技术网

C# 使用来自用户的数据更新.config文件

C# 使用来自用户的数据更新.config文件,c#,app-config,appsettings,C#,App Config,Appsettings,我正在尝试将一些设置保存到配置文件的appSettings部分,以便使用这些数据执行程序的过程。单击一个按钮,我希望将来自用户的数据保存在配置文件中。我使用的代码是: private void button1_Click(object sender, EventArgs e) { System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Configurat

我正在尝试将一些设置保存到配置文件的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文件中,我有什么遗漏吗?

config.Save(ConfigurationSaveMode.Modified)仅在修改exisint键时有效,换句话说,如果需要将键值添加到web配置中,只需调用config.Save()没有参数时

如果要向配置文件添加新密钥,需要先在设置集合中添加它:

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

然后调用Save方法。

边界复制。建议你吸收其中的信息并重新考虑你的问题。如果你使用“key1”和“key2”,你应该使用“roshane”或“email”……你想添加值还是修改现有值?是的,我知道它的标题使用了更新词,但在最后OP说添加了,所以你可能是对的。