In this article, we will talk about the config file used for a C# application. What is the goal of it, and how to use it. How to get values and create your own config section.

What is a config file?

It happens sometimes (quite often actually) that we need to store some parameters, default settings, framework or external libraries values and the config has been made for that purpose.

How to use the AppSettings?

We will first try to get a variable stored in the Config File (App.config or Web.config). Let’s say here we want to store a path to write some logs:

So here, the variable name is LogPath, and the value is C:\temp\log. Now in the code, we want to get the path to store our logs from the config file:

That was pretty easy. Now let’s do the same but for a collection.

How to create a custom config section?

Go to your config file and add a collection. Let’s say it’s a collection of Nodes. We will create a custom section in the config file called CustomConfigSection. We need first to register it in the configSections. Here is the complete config file for our simple example:

Here, we will have to create a new class defining the structure of our Config Section called CustomConfigSection:

How to consume values from a custom config section?

Now, in the code, we can get our custom config collection from the config file:

You should see something like this:

C# config file

Now if you want more details about the config file, here is a link on the official Microsoft page.

Happy coding!   😉