web analytics

How To Access Application Configuration File (App.config) Programmatically in C#?

Options

codeling 1595 - 6639
@2016-01-12 23:02:55

When you are creating a C# Windows application, you can store its configuratuion settings in a file called App.config, then you get the settings in that file through the property and method in System.Configuration.ConfigurationManager class:

  • Property: System.Configuration.ConfigurationManager.AppSettings
  • Method: System.Configuration.ConfigurationManager.GetConfig()

For example, suppose the content of the App.config is:

<?xml version="1.0" encoding="utf-8"?>
< configuration>
    <configSections>
        <section name="SupportedCultures" type="System.Configuration.NameValueSectionHandler"/>
    </configSections>
    <SupportedCultures>
        <add key="en-CA" value="English"/>
        <add key="fr-CA" value="French"/>
    </SupportedCultures>
    <appSettings>
        <add key="ApplicationName" value="My Test 1.0"/>
    </appSettings>
    <startup>
    </startup>
< /configuration>

Then you can use the code below to access the configuration:

string appName = ConfigurationManager.AppSettings["ApplicationName"];

NameValueCollection nvc = (NameValueCollection)ConfigurationManager.GetSection("SupportedCultures");

One advantage of the above ways is that except for the property reference and function call, you don't need to write any other code to get the configuration settings.

In some cases, you may want to access this configuration file programmatically, but the question here is how to know the path of the configuration file without hard coding? After some investigation, I just found a solution to the question, that is using the property: AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, it will return the file path of the configuration file. For example, the following C# code loads the configuration file into a XMLDocument object:

XmlDocument doc = new XmlDocument();

doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

After that you can do anything you want, for instance, the following C# code selects all culture nodes in the above configuration file using XPath expression:

 XmlNodeList cultureNodeList = doc.SelectNodes("//SupportedCultures/add");

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com