Posts Tagged ‘C#’

How to read and write settings in App.config with C#

Tuesday, September 9th, 2008

Today I’ve been working on creating a simple WPF application. As a part of this application, I want to store some user-defined preferences. This post briefly details how I went about doing this using C# and Visual Studio 2008.

First, make sure your application has an App.config file. If it is missing, add it by going to Project > Add New Item… and then selecting “Application Configuration File” from the pop up. Visual Studio will then add a blank App.config file to your application. Open it and make it look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="PreferenceToRemember" value="DefaultValue" />
</appSettings>
</configuration>

In order to write to this App.config file, you will need to add System.Configuration as a project reference. And of course you’ll need to have the appropriate usings statements on the right forms. Once all that is done, you can write to the App.config file with the following:

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

The last line in the code above refreshes the current in-memory configuration with what is saved inside the App.config file. To read from the App.config file, just use this:

string strPreferenceToRemember = ConfigurationManager.AppSettings["LastProject"];

As a final note, I noticed that nothing seemed to be written to the configuration file while debugging within Visual Studio, but once I published the application it worked as expected. I don’t know why this happens, but I’ll modify this post if I find out.