如何在运行时修改我的App.exe.config键?

Lou*_*hys 27 .net c# app-config

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

<appSettings>
    <add key ="UserId" value ="myUserId"/>
     // several other <add key>s
</appSettings>
Run Code Online (Sandbox Code Playgroud)

通常我使用访问值 userId = ConfigurationManager.AppSettings["UserId"]

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

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

Raf*_*jer 60

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

config.AppSettings.Settings["UserId"].Value = "myUserId";     
config.Save(ConfigurationSaveMode.Modified);
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关ConfigurationManager的信息

  • 您应该在该代码之后还有以下内容:ConfigurationManager.RefreshSection("appSettings"); (5认同)