다음을 통해 공유


ConfigurationManager class in C#

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 https://www.microsoft.com/info/cpyright.htm)

Comments

  • Anonymous
    January 01, 2003
    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