Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update appSettings in a WPF app?

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

like image 306
James McConnell Avatar asked Nov 20 '08 14:11

James McConnell


2 Answers

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.

like image 174
Dillie-O Avatar answered Nov 13 '22 15:11

Dillie-O


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

like image 1
Vincent Van Den Berghe Avatar answered Nov 13 '22 14:11

Vincent Van Den Berghe