• Why, Where, and How of.net Configuration Files
  • Written by Eric Lynch
  • The Nuggets translation Project

Overview of.NET configuration files

This article provides a quick overview of.NET configuration files and links to more in-depth information.

Update: The world is moving on. Most of the information in this article is now out of date. The preferred Configuration mechanism in the Microsoft NuGet. Now Extensions. The Configuration and the related package. For more details, see the documentation for the ConfigurationBuilder class in this link.

introduce

Having been using.NET profiles for many years, it would be helpful if I could provide a quick introduction.

In this article, there are many C# code examples, assuming that you include a reference to system.configuration. DLL in your project and add the following using statement to your code:

using System.Configuration;
Copy the code

To use the ConfigurationManager class that has access to configuration information, these two prerequisites must be met.

why

The.net Framework provides a rich set of classes and technologies to simplify application configuration. Essentially, all of these classes make it easier to read and write configuration information from XML configuration files.

Configuration files include a number of standard sections, custom sections for common.NET features, and the ability for developers to create their own custom configuration sections.

Standard sections have changed over time. Initially, standard job configuration is done primarily through the appSettings section, which contains name/value pairs for each setting. Later, transparent, type-safe support for configuration was provided through the generated C# Settings class and the corresponding applicationSettings and userSettings configuration sections.

Where (storage location)

Where can I find configuration files? This is a seemingly complicated problem. Because the configuration is hierarchical, it is possible to have multiple configuration files affecting an application. These include machine profiles, application (or Web) profiles, user local Settings, and user roaming Settings.

The machine configuration

Machine configuration files are grouped with.net Framework files that are not easy to find. The location of the configuration file depends on the.NET version and platform type (such as 64-bit) the application is using.

A typical example might be C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG\ machine-config.

In a C# application, the following code returns the location of the file:

System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() 
               + @"CONFIG\machine.config"
Copy the code

Application configuration

Application configuration files are usually in the same directory as the application. For Web applications, it is named web.config. For non-Web applications, the starting name is app.config. After the build, it is copied to the same name as the.exe file. So, for the program myprogram.exe, you can find myprogram.exe.config in the same directory.

In a C# application, the following code returns the location of the file:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
Copy the code

However, this is generally not recommended, as you may find that some programs change the location of the application configuration file, as shown below:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE"."NewName.config")
Copy the code

User Settings

User Settings files are almost impossible to find, perhaps by design. The name of the directory varies with the Windows version. To complicate matters further, the parent folder is usually hidden. The folder directory also contains the company name (application vendor), application name, unique identifier of the application, and version of the application.

An example of local user Settings on Windows 7 might look like this:

C: \ Users \ MyUsername \ AppData \ Local \ CompanyName \ MyProgram exe_Url_pnbmzrpiumd43n0cw05z2h4o23fdxzkn \ 1.0.0.0 \ user config

In the following C# code, you can get the base directories for local user Settings (line 1) and roaming user Settings (line 2) :

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Copy the code

In the following C# code, you can get the exact file paths for local user Settings (line 1) and roaming user Settings (line 2) :

ConfigurationManager.OpenExeConfiguration
                     (ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath
Copy the code

Other configuration

If that’s not confusing enough, there are other files to look at. Such as the root-level web.config (in the same directory as machine.config). In addition, the subdirectory of a Web application can be overridden with additional inherited Settings via web.config specific to that subdirectory.

Finally, IIS provides some of its own configuration. A typical location is: C:\Windows\System32\inetsrv\ applicationHost. config.

How to use

As mentioned earlier, the application configuration file is divided into a number of standard-like configuration sections. Here, we briefly discuss some of the most common configuration sections.

AppSettings section

The simplest standard configuration section is appSettings, which contains a collection of name/value pairs for each setting:


      
<configuration>
  <appSettings>
    <add key="MySetting" value="MySettingValue" />
  </appSettings>
</configuration>
Copy the code

In C#, you can reference a set value as follows:

string mySetting = ConfigurationManager.AppSettings["MySetting"];
Copy the code

ConnectionStrings section

Because database connections are so common in.net, a special configuration section is provided for database connectionStrings:


      
<configuration>
  <connectionStrings>
    <add name="MyConnectionStringName"
      connectionString="Data Source=localhost; Initial Catalog=MyDatabase; Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
Copy the code

In C#, you can get the connection string using the following code:

string connectionString = ConfigurationManager.ConnectionStrings[
  "MyConnectionStringName"].ConnectionString;
Copy the code

Initially, people may not know whether they need to refer to the ConnectionString property of “ConnectionString.” The actual connectionStrings section has a bad name. A better name would be connectionStringSettings, because each record contains a connection string and a database provider.

The syntax of the connection string is entirely up to the database provider. In this case, System.data.sqlClient is the most common database provider for Microsoft SQL Server databases.

ApplicationSettings and userSettings section

In.NET 2.0, Microsoft tried to make it easier to use configuration files. Therefore, a Settings file is introduced. A careful observer will notice that Settings is first located in the application configuration file and then copied to the user-set configuration file.

For Windows Forms and WPF applications, you can find a settings. Settings file in the Properties folder of your project. You can use this setting for the console and other applications as well. Open the project’s properties, then click the Settings button/TAB. You will see the option to add the default Settings file.

Add a screenshot of the default Settings file in the project “Properties” – “Settings” :

In general, you only need to edit the Settings file (or the project’s Settings) rather than edit the configuration file directly. The following examples are only used to demonstrate that these Settings do exist in the configuration file.


      
<configuration>
  <configSections>
    <sectionGroup name="userSettings"
      type="System. The Configuration UserSettingsGroup, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089">
      <section name="WinFormConfigTest.Properties.Settings"
        type="System. The Configuration ClientSettingsSection, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"
        allowExeDefinition="MachineToLocalUser"
        requirePermission="false" />
    </sectionGroup>
    <sectionGroup name="applicationSettings"
       type="System.Configuration.ApplicationSettingsGroup, System, 
       Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="WinFormConfigTest.Properties.Settings"
        type="System. The Configuration ClientSettingsSection, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"
        requirePermission="false" />
    </sectionGroup>
  </configSections>
  <userSettings>
    <WinFormConfigTest.Properties.Settings>
      <setting name="MyUserSetting" serializeAs="String">
        <value>MyUserSettingValue</value>
      </setting>
    </WinFormConfigTest.Properties.Settings>
  </userSettings>
  <applicationSettings>
    <WinFormConfigTest.Properties.Settings>
      <setting name="MyApplicationSetting" serializeAs="String">
        <value>MyApplicationSettingValue</value>
      </setting>
    </WinFormConfigTest.Properties.Settings>
  </applicationSettings>
</configuration>
Copy the code

To reference one of these Settings items, simply use the Settings class that was created automatically. The following is a typical reference:

string myUserSetting = Properties.Settings.Default.MyUserSetting;
string myApplicationSetting = Properties.Settings.Default.MyApplicationSetting;
Copy the code

Note: Properties is a namespace automatically created in the space of your application name.

To change the user’s Settings, simply assign a value to the property and save the changes, as follows:

Properties.Settings.Default.MyUserSetting = newValueForMyUserSetting;
Properties.Settings.Default.Save();
Copy the code

Update the Settings

Finally, release a new version of the application. At this point, you may encounter a common problem. Since user Settings are version-specific, they will be lost after the upgrade.

Fortunately, the framework anticipates this need and provides a way to upgrade. The typical way to handle this problem is with a user-set Boolean attribute Upgrade, with an initial value of false (when the application is first deployed).

Thus, typical code for handling upgrades (and keeping previous user Settings) looks like this:

if(! Properties.Settings.Default.Upgraded) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.Upgraded =true;
  Properties.Settings.Default.Save();
}
Copy the code

What’s next

In the previous section, you may have noticed the rather lengthy configSections section in the configuration file. This is how The Microsoft extension configuration file adds the new userSettings and applicationSettings sections.

This is also how you can add your own custom configuration sections.

In short, you can do this by extending the ConfigurationSection and ConfigurationElement classes. In each of the derived class, you will be using ConfigurationPropertyAttribute members such as attribute to modify.

Simple, right? Just kidding. Others have provided good descriptions of this slightly more complex but not too difficult mechanism. A link is provided at the end of this article for further reading.

Here, I just want to provide a few hints that might be overlooked in a longer description.

When all is said and done, you need to create an XML Schema Document (XML Schema Document — XSD file) that describes your sections and include it in your project. After opening the configuration file, you can use XML… The Schemas menu item ensures that intelligent prompts find XSD files.

Depending on the version of Visual Studio, you may hear complaints about the XMLNS property of the configuration section. If you do, there is a simple solution. I usually XmlnsConfigurationSection derived from my own middle class, rather than directly from ConfigurationSection derived. This keeps the problem from happening.

using System.Configuration;

namespace Extras.Configuration
{
  abstract public class XmlnsConfigurationSection : ConfigurationSection{[ConfigurationProperty("xmlns")]
    public string Xmlns
    {
      get { return (string)this["xmlns"]; }
      set { this["xmlns"] = value; }}}}Copy the code

Further reading

  • ASP.NET Configuration File Hierarchy and Inheritance
  • Unraveling the Mysteries of.NET 2.0 Configuration
  • Decoding the Mysteries of.NET 2.0 Configuration
  • Cracking the Mysteries of.NET 2.0 Configuration
  • System.Configuration Namespace
  • ConfigurationSection Class
  • ConfigurationElement Class
  • ConfigurationPropertyAttribute Class
  • ConfigurationElementCollection Class