Search code examples
c#.netvb.netapp-config

When/How Does My .NET Application Use Its App.Config File?


I've never thought about it before; but I recently learned how I could modify the app.config file to add/remove trace listeners (for example, to redirect all of the Trace.WriteLine output to a text file).

But I don't quite understand how it works? Can someone explain a bit?

I know the corresponding C# code to do the same as the config (in this example) - does that code get generated/executed before my application's entry point?


Solution

  • does that code get generated/executed before my application's entry point?

    Think of a config file just as a standard text file. If your application code doesn't read and do anything with it, nothing will happen. So basically when you define some section in the app.config file, there is some code in your application (either in the BCL or custom) that at some moment will read, parse and interpret the values.

    So, let's consider the example of trace listeners. When you try to trace something in your code, the underlying Trace class will use the config system to check the values you have defined in app.config. This config system parses the XML only once and stores it as singleton in memory to avoid the overhead everytime. So, it's only the first time you try to trace something that the config file is parsed and on subsequent calls the values are directly read from memory.