Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c# - How to modify my App.exe.config keys at runtime?

In my app.config I have this section

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

Usually I access the values using userId = ConfigurationManager.AppSettings["UserId"]

If I modify it using ConfigurationManager.AppSettings["UserId"]=something, the value is not saved to the file, and next time I load the application, it uses the old value.

How can I change the value of some app.config keys during runtime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

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

You can read about ConfigurationManager here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...