How to update appSettings in a WPF app?

2019-04-06 06:37发布

问题:

Greetings to all! This is my first question here on stackoverflow. I have a WPF application that I am writing for the fellow developers in my department, and there are a couple of settings that I need to check for at startup and update if they are not set (one is the location of an executable on the users computer, we all have it, just not in the same place). So when my app starts up for the first time, I need to pop a filechooser to have them select the location.

What I need to do is write the location of that to the appSettings, but I just can't seem to get it, and I searched Google pretty hard last night trying to find a way to do it. Most answers I saw involved reading the app.config file as straight XML, and that doesn't seem right.

So, I just need a way to update values in the appSettings for my application. I can read from them just fine, just haven't figured out how to write to them. Thanks so much!

James

回答1:

Have you looked into the ConfigurationManager class? It provides a more robust interface to the app.config file and you can do something like this:

Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = “NewValue”;
oConfig.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection(”appSettings”);

Just remember to import System.Configuration into your project. It isn't added by default.



回答2:

Take a look at the Configuration class and Enterprise Library. You can find detailed instructions here.