C# 如何在运行时修改我的App.exe.config密钥?

C# 如何在运行时修改我的App.exe.config密钥?,c#,.net,app-config,C#,.net,App Config,在我的app.config中,我有这个部分 <appSettings> <add key ="UserId" value ="myUserId"/> // several other <add key>s </appSettings> //其他几个 通常我使用userId=ConfigurationManager.AppSettings[“userId”] 如果我使用ConfigurationManager.AppSetti

在我的app.config中,我有这个部分

<appSettings>
    <add key ="UserId" value ="myUserId"/>
     // several other <add key>s
</appSettings>

//其他几个
通常我使用
userId=ConfigurationManager.AppSettings[“userId”]

如果我使用
ConfigurationManager.AppSettings[“UserId”]=something
修改它,则该值不会保存到文件中,下次加载应用程序时,它将使用旧值

如何在运行时更改某些app.config键的值

旁注

如果您的app.config中的某些内容需要在运行时进行更改,那么可能有更好的地方保存该变量

App.config用于常量。在最坏的情况下,使用一次性初始化

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

config.AppSettings.Settings["UserId"].Value = "myUserId";     
config.Save(ConfigurationSaveMode.Modified);

更改值后,您可以阅读有关ConfigurationManager的信息,可能您不会保存Appconfig文档

// update    
  settings[-keyname-].Value = "newkeyvalue"; 
//save the file 
  config.Save(ConfigurationSaveMode.Modified);   
//relaod the section you modified 
  ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 

在我的回答中添加了vb代码的c#代码使用app.config有一些特殊的类-你不必这样做manualy@RafałSpacjer-我知道你可以选择.net framwork中已经提供的特殊类,但这只是我在项目中应用的一个解决方案,但我不认为每个轮子都发明是一个好主意我们该做点什么了。所需的功能可以在3行代码中完成,而不是超过10行。可能不需要重新写入整个文件,只需更改一个元素。既然这3行代码可以做到这一点,那么它肯定会在更多的行中完成更多的实际“工作”。在使用的地方,这最终是一行代码。;)app.config不是只在编译时使用吗?因此,myExecutable.exe.config等。我同意,但是在某些情况下,连接字符串可能不适当地以明文形式输入,并且您希望即时对其进行加密。如果您希望继续使用默认配置管理器,但能够在启动时加载外部配置文件,这是必要的。应用程序开始或结束时的运行时仍然是运行时。对我来说,最好不要仅仅为了简单而使用额外的文件。如果已经有了一个.config文件,并且可以在没有冲突的情况下使用它,为什么还要在文件夹中有一个额外的文件呢?在单元测试之外,我非常同意。但是,在单元测试的上下文中,能够动态更新配置值以增加测试覆盖率是非常方便的;
// update    
  settings[-keyname-].Value = "newkeyvalue"; 
//save the file 
  config.Save(ConfigurationSaveMode.Modified);   
//relaod the section you modified 
  ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);