ConfigurationManager class in C#

ConfigurationManager class in C#

  • Comments 2
  • Likes

The ConfigurationManager class in C# has been one of my latest discoveries for storing all the configuration data required by an application. Here is one example of how I used it to store some of my configuration data:

Let us say that you have written an application (let's call is Foo.exe). Now let us say that Foo.exe logs some information and it requires the log file location to be passed in as an input via configuration info.

So, here is what you could do. 

 

1. Add an Application Config file to Foo.exe (You could do this on Visual Studio via Add > New Item > Application Configuration File). Let us call it Foo.config

 

2. Open Foo.config. It'll look something like this:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

</configuration>

 

 3. Add the following lines into Foo.config between the <configuration> </configuration> tags:

<appSettings>

<add key="LoggingFile" value="C:\Logs\Foo.log" />

</appSettings>

 Where the key " LoggingFile" is the key, querying the value of which will fetch you the log file path.

 

4. Now within your application, here is how you can fetch the value of " LoggingFile":

using System.Configuration;

string logFilePath = ConfigurationManager.AppSettings["LoggingFile"]

 

Wasn’t that easier than writing your own XML based config files and a parser to fetch the values from it? Hope this helps.


(This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm)

Comments
  • Is something missing here? How does the ConfigurationManager know the name of the configuration file? I tried this and get a System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty]' is inaccessible due to its protection level in the code on the file and get numerous "Could not find schema information for the attribute 'key'." for the configuration file. Is there an example that works?

    Thanks,

    -Scott

  • The problem is that it seems to be pretty hard to point to a specific location with ConfigurationManager. However, I solved the problem with default file and with copying the file together with application.

    If you are using Visual Studio the default config file will be under your project folder saved in format applicationName.exe.config. When you move your application to the production environment you need to copy file applicationName.exe.config together with your applicationName.exe in same folder in order application to be able to read config file contents.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment