App.config settings in C#

Hi again!

I usually work with web pages but the other day I worked with a simple application to get some data from a file using the ODBC driver, but this desktop application must have some settings that I need to configure, here is where app.config file have their special moment.

Work with the app.config is like the web.config file talking about web projects, so its easy and very helpful to create a program with settings.

We need to add an app.config file to our project, just click in the Project, Add, New Item and select Application Configuration File.

Open the file and it will be like this (without the key setting, that is my default setting I added to the file) :

<?xml version="1.0" encoding="utf-8" ?>
    <add key="setting" value="HelloWorld!"/>

Then in code, we need the assembly we need to manage the configuration file:

using System.Configuration;

Actually is very easy, to read a configuration just do this:

// Read values from configuration
string setting = ConfigurationManager.AppSettings["setting"];

To write a new value, remove an old one or modify an existent one, just do this:

// Write values from configuration
// Modify
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["setting"].Value = "Hello_World!";
// Add
config.AppSettings.Settings.Add("modifDate", DateTime.Now.ToLongTimeString() + " ");
config.AppSettings.Settings.Add("modifDate2", DateTime.Now.ToLongTimeString() + " ");
// Remove

Ok now you can create settings for your application,


4 thoughts on “App.config settings in C#

  1. says:

    Great post, I believe website owners should larn a lot from this site its rattling user pleasant. So much wonderful info on here :D.

  2. Thomas Fairris says:

    This helps me a lot! I am a VB programmer (kind of) and am wanting to learn C#. So used to the my.settings in VB that I got lost in C# trying to read from and save to the settings. This would be VERY useful on the typed datasets changing the connection string at runtime. Thank You for this code.

  3. When I use this method (in Visual Studio 2012 and with WPF), I get an error saying it is obsolete, and has been replaced with “System.Configuration.ConfigurationManager.GetSection()”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: