Reading Configuration Files in C#

A common task for developers is to store application specific configuration. There are many ways you can take to get that functionality. If you use .Net / C# you can use the simple, built-in way to work with configuration files. Let’s look how this works.

 

Create an app.config or web.config

Right click on the project node in the Solution Explorer -> Add -> New Item -> Application Configuration File. This will add an app.config file to your project. Visual Studio checks if the project you selected is a web project and if so, it will create a web.config file instead. They follow the same rules and in either case you get the same benefits.

In the app.config file you can add a section called appSettings to store your values. A full example of an app.config with a property to specify a sender email address can look like this one:

 

Use the ConfigurationManager to read it

The class ConfigurationManager offers you a simple way to read the configuration values. Reference the system package System.Configuration and add a using statement for it. You now can read your configuration values like an array:

The benefit of storing your configuration values outside of your code is that you can come back later and only change the values in a simple text file. You don’t need to recompile your code to use the new settings.

 

Reading the connection string

The connection strings for your database have their own section called <connectionStrings>. To read the connection string for the database PagingDb as specified in the app.config example above, you can use this line of code:

While your configuration settings may not change that much, you should always save your connection strings outside of your application. You should use a different database for development, test and production. If your connection string is stored in the app.config, you can simply replace it without recompiling your code.

 

Conclusion

When you follow the built-in way and don’t reinvent the configuration management wheel, you not only save a lot of time, but other tools can work with this approach as well (such as Octopus Deploy).

Don’t fight the framework, use it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.