How to add a configuration file (app.config) to your #C application?


This article shows how to add a simple configuration file (app.config) to your #C project. Sooner or later, you need to change a value such database connection string or username. By adding an application configuration file (app.config file) to a C# project, you can customize how the common language runtime locates and loads assembly files which means you can create keys to be used on your project without need to recompile it everytime you need to update some value.


What is App.config?

At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A “configuration section” is a snippet of XML with a schema meant to store some type of information.

Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.

Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.

Application-level config files inherit settings from global configuration files, e.g. the machine.config.

Reading from the App.Config

Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:

<?xml version="1.0"?>
           <add key="ConnectionType" value="MSSQL" />

Once you have defined your app.config, you can read it in code using theĀ ConfigurationManager class. Don’t be intimidated by the verbose MSDN examples; it’s actually quite simple.

Continue reading “How to add a configuration file (app.config) to your #C application?”

3.7/5 - (3 votes)