Click here to Skip to main content
15,301,414 members
Articles / Programming Languages / XML
Posted 10 Jul 2006


418 bookmarked

Read/Write App.Config File with .NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.88/5 (121 votes)
10 Jul 2006CPOL9 min read
Learn what .NET 2.0 offers you to read/write App.Config files


This is my first CodeProject article. I would like to show you the most important changes in the System.Configuration namespace with .NET 2.0. I have looked at my blog referrer statistics and saw about 20 hits/day by Google. Most of them were searching information on how to configure the new Enterprise Library but there are also a significant number of people that seem to seek answers to the following questions:

  • How to read/write to App.Config?
  • How to store a list of objects in a config file via the System.Configuration mechanism?

Reason enough for me to shed more light on the System.Configuration namespace. The main changes from .NET 1.0/1.1 in the System.Configuration namespace are:

  • Write to your App.Config file through the Configuration class
  • New configuration model for Windows Forms applications
  • Store complex objects including object collections in your App.Config File
  • It is possible to store Connection Strings in the App.Config file. See ConnectionSettings which enables you to store your settings on an SQL Server. The Enterprise Library for Sample SqlConfiguration exercises this by implementing a SqlConfigurationSource which can store and retrieve a ConfigurationSection

So where to start? I think first I will show you the config file and explain how you can create it programmatically in your application.

The easiest way to read/write AppSettings

If you want to store only key/value pairs in your App.config file there is a special section in reserved which allows you to do exactly that. Simply add an <appsettings> section and add your data as key/value pairs of the form <add key="xxx" value="xxxx" />. That's all to create a new app.config file with settings in it.


<?xml version="1.0" encoding="utf-8" ?>
    <add key="Setting1" value="Very" />
    <add key="Setting2" value="Easy" />

The data access API has been changed for this type of setting with .NET 2.0. The "old" one liner ConfigurationSettings.AppSettings has been deprecated in favor of ConfigurationManager.AppSettings. Apart from the naming change you can now also write your application settings. For read only access you can look at the ShowConfig function defined below. Writing the last modification time is demonstrated in the Main function.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace AppSettings
   class Program
     static void ShowConfig()

        // For read access you do not need to call OpenExeConfiguraton
        foreach(string key in ConfigurationManager.AppSettings)
           string value = ConfigurationManager.AppSettings[key];
           Console.WriteLine("Key: {0}, Value: {1}", key, value);

     static void Main(string[] args)


        // Open App.Config of executable
        System.Configuration.Configuration config =

        // Add an Application Setting.
                       DateTime.Now.ToLongTimeString() + " ");

        // Save the changes in App.config file.

        // Force a reload of a changed section.

Expected Output:

Key: Settings1, Value: Very
Key: Setting2, Value: Easy
Key: Settings1, Value: Very
Key: Setting2, Value: Easy
Key: Modification Date, Value: 01:21:03

With this mechanism you can read and update simple key/value pairs within your application without digging any deeper in the System.Configuration namespace. The following examples show the other features like the new Windows forms configuration mechanism, create your own configuration section and how you can easily store lists of objects in the App.config file with the new Enterprise Library helper classes.

Using the MySettings Feature

When developing Windows Forms with VS2005 you get for free a new configuration mechanism. The Windows Forms designers were so nice to create an access class automatically from your config values and came up with a consistent model to store application global config files in the app.config.exe file and user specific settings within the user profile in user.config. Please note that the Forms configuration model is not available in class library projects since you have no App.config file for your DLL. When you add a settings file to your class library project you can merge the settings with the App.config file of your hosting executable. This can be useful if you want to enforce that every application that uses your library can have its own settings inside the App.config file of the executable. You have the freedom to store your settings wherever you would like to. Any provider can be plugged into your config data access class by decorating your configuration class with the SettingsProviderAttribute. If none is specified, the LocalFileSettingsProvider is used which relies on System.Configuration. This is the reason why you do not need to reference the System.Configuration assembly in a Windows form, but you see the System.Configuration assembly loaded in your Windows forms application. You can check it with the debugger in the loaded modules list.

Below is a new Windows Forms project shown which was generated via New->Project->Windows Application. The new configuration features are visible in the Properties folder of your project. There go your resources and the automatically generated strongly typed resource access class with static properties to allow easy and type safe access to your resources. This is similar to the old C programming model with Windows resources. You had an header file with resource ids generated by the resource compiler which spits out a header file which is compiled (compile time checking of the existence of resources) and an object file which is linked into your target. Now you have also compile time checking in .NET if you access your resources via the static properties.

The configuration features surface in the auto generated Settings.settings file and Settings.Designer.cs. To create new configuration values you have full Designer integration within Visual Studio (see picture below). In your code you can read/modify these settings via the generated access class. Inside the visual editor you can choose between two scopes for each of your configuration settings: Application and User. The Application scope defines configuration values which cannot be changed by the user and are the same for all users of this application. User scoped settings on the other hand can be changed/created by, well the users and are stored within their local profile. Application scoped settings cannot be altered when you save your settings. Only the user settings are written to disk during a save operation!

User Specific Application Settings

VS 2005 generated Windows Forms application skeleton.

(Generated by Visual Studio)

<?xml version='1.0' encoding='utf-8'?>
   <Profiles />
       <Setting Name="testSetting" Type="System.String" Scope="User">
            <Value Profile="(Default)">Form1</Value>

(Generated by Visual Studio using the SettingsSingleFileGenerator as Custom Build Tool)

namespace WindowsApplication1.Properties
    internal sealed partial class Settings :
       private static Settings defaultInstance = ((Settings)
           new Settings())));

       public static Settings Default
          get { return defaultInstance; }

       public string testSetting
          get { return ((string)(this["testSetting"]));   }
          set { this["testSetting"] = value;              }

To load your settings programmatically, you only need to do a:

Settings set = Settings.Default;

and access your settings via the property of the returned instance.

string str = set.testSetting;

Wow that was easy. Wasn´t it? Now let's save our changed test setting:

set.testSetting = "test value";

That's pretty much it. To display some of your settings in your form you can use data binding and let your users configure the application font, color, .... User specific settings are stored in %APPDATA%\<AppName>\<AppName><AppConfigName_GUID>\<AssemblyVersion>\user.config. The path to the user config on my machine is e.g. %APPDATA%\WindowsApplication1\WindowsApplication1.exe_Url_x00ebzylso3e0rtwd1pnxkhduwr34pgb\ This enables you to install a Windows Forms App as Administrator for all users with some global settings in the executable App.config and user specific settings which are stored in the user profile. If your users are in a domain with a roaming profile they will get the same profile and thus the same user settings on every computer they work.

Is this new mechanism compatible with the old one?

Yes it is. Even more: these nice classes do rely heavily on the System.Configuration features. Each user/application section is put into its own ConfigurationSectionGroupCollection which can be accessed programmatically. Every group does contain one or more configuration section/s of the type ClientSettingsSection which serves as a container for your strongly typed key/value pairs. The following code enumerates all your auto generated settings and prints them out to the Console.

   // Get the application configuration file.
   System.Configuration.Configuration config =

   // Get the collection of the section groups.
   ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;

   // Show the configuration values

   static void ShowSectionGroupCollectionInfo(
          ConfigurationSectionGroupCollection sectionGroups)
        ClientSettingsSection clientSection;
        SettingValueElement value;

        foreach(ConfigurationSectionGroup group in sectionGroups)
        // Loop over all groups
            // Only the ones which are actually defined in app.config

            Console.WriteLine("Group {0}", group.Name);

               // get all sections inside group
            foreach(ConfigurationSection section in group.Sections)
              clientSection = section as ClientSettingsSection;
              Console.WriteLine("\tSection: {0}", section);

              if(clientSection == null)

              foreach(SettingElement set in clientSection.Settings)
                   value = set.Value as SettingValueElement;
                   // print out value of each section
                   Console.WriteLine("\t\t{0}: {1}",

How To Read/Write Another App.Config File

To open another App.Config file, you need to create an instance of <a href="">ExeConfigurationFileMap</a>. The purpose of this class is not that obvious but we can use it to open another file. Once you have learnt this little trick the rest is easy. Here is a little example that opens a file by specifying it's name, makes some changes to it and writes the changes to disk.

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"ConfigTest.exe.config";
                    // relative path names possible

// Open another config file
Configuration config =

//read/write from it as usual
ConfigurationSection mySection = config.GetSection("mySection");
config.SectionGroups.Clear(); // make changes to it

config.Save(ConfigurationSaveMode.Full);  // Save changes

The Microsoft Enterprise Library way has a shorthand utility class for this. It is the FileConfigurationSource which hides those strange things. Tom Hollander has a nice post explaining this already so I will not repeat the same here.

How To Read/Write Serialized Objects

A more advanced way to store our settings is to create our own ConfigurationSection. This makes our configuration values distinguishable from other configuration values inside the App.config file. It is a little more complicated since you have to write your own class whose content is de/serialized to the App.config file. I am going to show you at first the config file and then explain what code you need to write to read/save these settings to your application configuration file.

App.Config (Taken from the Enterprise Library Configuration Migration QuickStart Sample)


        <section name="EditorSettings"
                 ConfigurationMigrationQuickStart, Version=,

  <EditorSettings name="Verdana" size="24" style="2" />


Most App.config files which contain config data have a <configSections> element where many <section> are defined. The name attribute of a section (in this example "EditorSettings") tells the config system that the class ConfigurationMigrationQuickStart.EditorFontData is responsible for the ser/deserialization of the node <EditorSettings>. The EditorFontData class derives from the <a href=",VS.80).aspx">ConfigurationSection</a> class and uses the <a href=",VS.80).aspx">ConfigurationProperty</a> attribute to create a mapping between the properties to de/serialize and the attribute names in names in the App.Config file.

using System.Text;
using System.Configuration;

public class EditorFontData : ConfigurationSection
    public EditorFontData()

    public string Name
       get { return (string)this["name"]; }
       set { this["name"] = value; }


    public float Size
       get { return (float)this["size"]; }
       set { this["size"] = value; }

    public int Style
       get { return (int)this["style"]; }
       set { this["style"]= value; }

To access an EditorFontData instance with values from your config file you only need to call: EditorFontData configData = ConfigurationManager.GetSection("EditorSettings") as EditorFontData;

Please note that the System.Configuration.ConfigurationManager returns only objects with read only properties. Subsequent calls to GetSection use the cached instance inside the ConfigurationManager. This constraint requires you to create every time a new instance for you e.g. EditorFontData object if you want to write to the App.config file. You even cannot add an object with the same name twice to the System.Configuration.Configuration object. Now comes the fun part: To edit an existing App.config file you have to remove your config object and then add a new object instance to the Configuration object. Only then the Save will succeed.

EditorFontData configData = new EditorFontData();

configData.Name = "Arial";
configData.Size = 20;
configData.Style = 2;

Configuration config =

// You need to remove the old settings object before you can replace it
// with an updated one
config.Sections.Add("EditorSettings", configData);
// Write the new configuration data to the XML file

To get your hands on the System.Configuration.Configuration object you have to open your App.Config file. The .NET config mechanism supports setting inheritance from the Machine.config from which all settings are inherited. Next comes the App.Config file which is selected by the ConfigurationUserLevel.None file.

Points of Interest

  • There is much more to this topic which can be found at my blog. This includes an SQL Server Import tool to store your App.config settings inside SQL server with the help of the (patched) Microsoft Enterprise Library.
  • When you use the MySettings Feature and add a settings collection with an auto generated settings class you will receive in the Appdomain.CurrentDomain.AssemblyResolve event handler the request for a not existing "System.XmlSerializers" assembly. This has something to do with the on the fly generated assemblies by XmlSerializer but I do not understand why I should know about this. In the handler I had to alter my application logic to skip this not existing assembly. If you consider this a bug you can vote here.
  • When you receive the error "Cannot add a ConfigurationSection that already belongs to the Configuration." then you did forget to remove the existing section. You cannot alter a section since it is read only. To replace it you must first call remove and then add to set your new one.


Released v1.0 on CodeProject which is based on my article at my blog which also dives into more details regarding the Enterprise Library Configuration system.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alois Kraus
Systems Engineer Siemens
Germany Germany
He is working for a multi national company which is a hard and software vendor of medical equipment. Currently he is located in Germany and enjoys living in general. Although he finds pretty much everything interesting he pays special attention to .NET software development, software architecture and nuclear physics. To complete the picture he likes hiking in the mountains and collecting crystals.

Comments and Discussions

Questionthis isn't working in wpf - vs2013 Pin
edwincool_20005-Jun-15 6:02
Memberedwincool_20005-Jun-15 6:02 
QuestionGood artical Pin
Praboda Lakruwan1-Apr-15 20:08
MemberPraboda Lakruwan1-Apr-15 20:08 
QuestionWriting to wrong App.config file Pin
wcdeich425-Nov-14 10:28
Memberwcdeich425-Nov-14 10:28 
GeneralMy vote of 5 Pin
srilekhamenon30-Oct-14 20:37
professionalsrilekhamenon30-Oct-14 20:37 
QuestionAdd section with keys Pin
Member 103594645-Jun-14 21:34
MemberMember 103594645-Jun-14 21:34 
GeneralMy vote of 5 Pin
qiaolijin15-Oct-12 16:44
Memberqiaolijin15-Oct-12 16:44 
Questionnice article Pin
hassan wasef21-Jul-12 5:19
Memberhassan wasef21-Jul-12 5:19 
QuestionSimplified example. Pin
ZamirF7-Jun-12 15:00
MemberZamirF7-Jun-12 15:00 
GeneralMy vote of 5 Pin
Md. Marufuzzaman28-Nov-11 3:27
professionalMd. Marufuzzaman28-Nov-11 3:27 
GeneralWow, excellent. Pin
Watcharakorn Wanich3-Jul-11 18:52
MemberWatcharakorn Wanich3-Jul-11 18:52 
GeneralMy vote of 5 Pin
Arthur Liberman26-Jun-11 2:35
MemberArthur Liberman26-Jun-11 2:35 
GeneralMy vote of 5 Pin
Omar Elsherif23-Jun-11 5:29
MemberOmar Elsherif23-Jun-11 5:29 
GeneralMy vote of 5 Pin
masmasi20-Jun-11 22:22
Membermasmasi20-Jun-11 22:22 
QuestionPreserve Formatting Pin
evoluzion18-Jan-11 8:36
Memberevoluzion18-Jan-11 8:36 
GeneralMy vote of 4 Pin
poteb14-Dec-10 20:57
Memberpoteb14-Dec-10 20:57 
GeneralProblem with writing config Pin
StNickolay4-Aug-10 21:32
MemberStNickolay4-Aug-10 21:32 
GeneralRe: Problem with writing config Pin
Alois Kraus4-Aug-10 21:59
MemberAlois Kraus4-Aug-10 21:59 
GeneralExample on a app.config read Pin
joe90992-Nov-09 13:14
Memberjoe90992-Nov-09 13:14 
GeneralRead/Write App.Config File with .NET 2.0 Pin
Member 562249219-Oct-09 0:00
MemberMember 562249219-Oct-09 0:00 
Generalgreat article Pin
Donsw17-Feb-09 14:38
MemberDonsw17-Feb-09 14:38 
GeneralChange SingleTagSectionHandler Pin
JPrinz24-Oct-08 4:04
MemberJPrinz24-Oct-08 4:04 
Generalgroup.IsDeclared always return false Pin
edw7615-Oct-08 5:58
Memberedw7615-Oct-08 5:58 
GeneralStrange Behavior....HAAAALLLLPPPP!!!! Pin
Figmo27-Oct-08 8:04
MemberFigmo27-Oct-08 8:04 
GeneralRe: Strange Behavior....HAAAALLLLPPPP!!!! Pin
Alois Kraus9-Oct-08 9:03
MemberAlois Kraus9-Oct-08 9:03 
Generalencoding app.config file Pin
kiquenet.com24-Sep-08 8:23
professionalkiquenet.com24-Sep-08 8:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.