SoFunction
Updated on 2025-04-14

C# configuration file and detailed explanation

1. Introduction

In C# application development, configuration files are like the butler behind the scenes, silently managing various settings of the application. Today, let’s explore in-depth two extremely important configuration files in C#: and. Whether it is developing Windows applications or building web applications, they play a key role. By rationally using these two configuration files, developers can easily adjust the behavior of the application without cumbersome modifications to the code, greatly improving development efficiency and application flexibility. Next, let us unveil their mystery together!

2. First acquaintance:

2.1 Definition and uses of both

Is a configuration file for Windows applications (such as console applications, Windows Forms applications). It is like a precision settings box, which stores various configuration information required by the application, such as database connection strings, application default settings, etc. in XML format. This storage method allows developers to change the application behavior without recompiling the entire project when maintaining and adjusting the application in the later stage. They only need to easily modify the relevant configurations in the file to achieve changes in application behavior. For example, in a Windows Forms financial management application, the database connection string can be easily configured. When the database server address changes, directly modify the address information in the configuration file, and the application can successfully connect to the new database.

And it is the capable configuration assistant for web applications. It assumes the heavy responsibility of storing web application configuration settings, including but not limited to authentication methods, authorization rules, page compilation settings, etc. Taking a web application in an online mall as an example, you can configure the user's authentication mode to form verification, and specify the URL of the login page. You can also set the page's compilation and debugging mode. It can be set to debug mode during the development stage to detect errors in a timely manner. After going online, switch to publish mode to improve performance.

2.2 What are the same and the differences

From a structural perspective, it is very similar to , both adopt the XML format and has a clear hierarchy as the root node, which contains multiple child nodes for storage of different types of configuration information.

They have a clear division of labor in terms of applicable scenarios. Focus on the configuration of Windows applications, and serve the web applications wholeheartedly. For example, a desktop version of the drawing software uses default settings such as brush color and canvas size; while a web application for online drawing relies on configuring user access rights, page layout style and other web-related settings.

Some configuration nodes are common in both, such as nodes, which are used to store simple key-value pair configuration information. In a cross-platform news reading application, whether it is the Windows desktop or the web, the URL of the news source can be configured through the node. However, there are also some nodes that are unique to each. For example, the <> node in the application is used to fully configure various web-related features such as authentication, authorization, session status, etc.; while there is no such specific node in it, because Windows applications do not need to handle these web-related functions.

3. Create simple examples to gain insight into

3.1 Create and configure C# console applications based on

3.1.1 Create a new console application project

Open Visual Studio and click "Create New Project" in the starting page. In the "Create New Project" dialog box that pops up, select "Language" to "C#", "Platform" to select "Windows", and "Project Type" to select "Console". Next, in the middle project template list, select "Console Application (.NET Core)" (if you are using the .NET Framework, you can select the corresponding console application template), enter the project name at "Name" below, such as "ConsoleAppConfigDemo", set the "Position" and "Solution Name", click the "Create" button, and a brand new C# console application project will be created.

3.1.2 Writing core code

Find the "" file in the project and double-click to open it. Enter the following code in it:

using System;
using ;
namespace ConsoleAppConfigDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read the value in the configuration file            string appName = ["AppName"];
            int portNumber = Convert.ToInt32(["PortNumber"]);
            ("Application Name: " + appName);
            ("Speaker port: " + portNumber);
            ();
        }
    }
}

In the above code, the configuration values ​​defined in the file are obtained by introducing a namespace. Among them, AppName and PortNumber are the key names we will configure in the file in the future.

3.1.3 Build and configure files

In the project's Solution Explorer, right-click the project name and select Add -> New Item. In the Add New Item dialog box that pops up, select Application Profile, keep the default name "", and click the "Add" button. At this point, a file is generated in the project.

Add the following content to the file:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;!-- Configure the application name --&gt;
    &lt;add key="AppName" value="My console app"/&gt;
    &lt;!-- Configure the listening port --&gt;
    &lt;add key="PortNumber" value="8080"/&gt;
  &lt;/appSettings&gt;
&lt;/configuration&gt;

In this configuration, the node is used to store configuration information in the form of a series of key-value pairs. The tag is used to add specific configuration items, where the key attribute specifies the key name of the configuration item and the value attribute specifies the corresponding value. For example, the corresponding value of the AppName key here is "My Console Application", and the corresponding value of the PortNumber key is "8080".

3.2 Create and configure based on web applications

3.2.1 Create a new web application project

Open Visual Studio and click "Create a new project". In the Create New Project dialog box, press Language to select C#, Platform to select Web, Project Type to select “Project Type”. Select "Web Application (.NET Core)" in the intermediate template list (if based on the .NET Framework, select the corresponding Web Application template), enter the project name below, such as "WebAppConfigDemo", set the storage path and solution name, and click "Create". In the "Create Web Application" dialog box that pops up, select the appropriate template, such as "Empty" template, and then click "Create" and the project creation is completed.

3.2.2 Writing Web Application Code

Find the "Pages" folder in the project (if you are using traditional Web Forms, find the "" file), and add the following code to the "" file:

using System;
using ;
using ;
namespace 
{
    public class IndexModel : PageModel
    {
        public string AppName { get; set; }
        public int PortNumber { get; set; }
        public void OnGet()
        {
            // Read the value in the configuration file            AppName = ["AppName"];
            PortNumber = Convert.ToInt32(["PortNumber"]);
        }
    }
}

In the above code, the configuration value is read from the file. The AppName and PortNumber attributes are used to display the read configuration information on the page. The OnGet method is called when the page is loaded and is responsible for obtaining data from the configuration file.

At the same time, add the following code to the "" file to display the configuration information:

@page
@model 
@{
    ViewData["Title"] = "front page";
}
&lt;div&gt;
    &lt;p&gt;Application Name: @&lt;/p&gt;
    &lt;p&gt;Listen to port: @&lt;/p&gt;
&lt;/div&gt;

This code uses @Model to access properties in IndexModel, and displays the application name and listening port read from the configuration file on the page.

3.2.3 Generate and configure files

If the project is based on Core, after the project is created, the file will be automatically generated in the root directory (if not, you can add it manually). If it is based on traditional Web Forms, files will also be automatically generated.

Add the following content to the file:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;!-- Configure the application name --&gt;
    &lt;add key="AppName" value="My Web Application"/&gt;
    &lt;!-- Configure the listening port --&gt;
    &lt;add key="PortNumber" value="8080"/&gt;
  &lt;/appSettings&gt;
  &lt;&gt;
    &lt;compilation debug="true" targetFramework="4.8" /&gt;
    &lt;httpRuntime targetFramework="4.8" /&gt;
  &lt;/&gt;
&lt;/configuration&gt;

In this configuration, the role of the node is similar to that in it, and is used to store configuration information in the form of key-value pairs. <>Node is an application-specific configuration node, where the tag is used to configure compilation-related settings. debug="true" means that debug mode is enabled, which facilitates debugging code during development; targetFramework specifies the .NET Framework version used by the application. The tag is used to configure the runtime settings of the application, and the targetFramework also specifies the .NET Framework version.

4. In-depth analysis of key nodes of configuration files

4.1 appSettings node

In C# configuration files, nodes are like a flexible "small repository" that are specifically used to store various simple configuration data. It organizes information in the form of key-value pairs, allowing us to easily define and obtain the configuration items required by the application. For example, in an image processing application, the default image saving path can be set in the node. Add the following configuration in the or file:

<appSettings>
    <add key="DefaultImageSavePath" value="C:\Images\Saved\" />
</appSettings>

In the code, get the configuration value by:

using ;
string savePath = ["DefaultImageSavePath"];

In this way, this configuration value can be easily used in different parts of the application. When you need to modify the default save path, you can change it directly in the configuration file without recompiling the code.

4.2 connectionStrings node

Nodes are of paramount importance for applications that need to interact with databases. It is specifically used to define database connection strings, which contain the key information required to connect to the database, such as the database server address, database name, user name, password, etc. Taking connecting to SQL Server database as an example, you can configure it in the file as follows:

<connectionStrings>
    <add name="MyDbConnection" 
         connectionString="Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword" 
         providerName="" />
</connectionStrings>

In the above configuration, the name attribute specifies a unique name for the connection string, which is convenient for reference in the code; the connectionString attribute defines the parameters for connecting to the database in detail; the providerName specifies the database provider.

In the code, get and use the connection string as follows:

using ;
using ;
string connectionString = ["MyDbConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Perform database operations    string query = "SELECT * FROM YourTable";
    SqlCommand command = new SqlCommand(query, connection);
    ();
    // Process query results    SqlDataReader reader = ();
    while (())
    {
        // Read data    }
    ();
}

Correctly configuring nodes can ensure stable and accurate connections between applications and databases, providing a solid foundation for data storage and reading.

4.3 Node (for applications)

<>Nodes are the core part of application configuration, covering all key aspects of web applications running.

In terms of compilation settings, configuration is performed through child nodes. For example:

<>
    <compilation debug="true" targetFramework="4.8">
        <assemblies>
            <add assembly=", Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </assemblies>
    </compilation>
</>

Here debug="true" means that debug mode is enabled during the development stage to facilitate timely discover and resolve problems in the code; targetFramework specifies the .NET Framework version used by the application. Children are used to add the assembly references required by the application.

In terms of authentication, the <> node also plays a key role. Taking form authentication as an example, the configuration is as follows:

<>
    <authentication mode="Forms">
        <forms loginUrl="~/Account/" timeout="30" />
    </authentication>
</>

In the above configuration, mode="Forms" specifies the use of form authentication mode, loginUrl specifies the URL of the login page, and timeout sets the timeout after the user login.

In addition, the <> node can also configure many settings closely related to the operation of web applications, such as authorization rules, session status, page processing, etc., which are closely related to the operation of web applications, and fully control the behavior and performance of the application.

5. Proficient in the use of configuration files

5.1 Read information in the configuration file

In C#, it is extremely common to read information in configuration files. The most common way is to use classes. For example, when we want to read the configuration value in the appSettings node, assume that there is the following configuration in the or file:

<appSettings>
    <add key="DatabaseServer" value="YourServerName" />
    <add key="DatabaseName" value="YourDatabaseName" />
</appSettings>

In the code, easily get it by:

using ;
string server = ["DatabaseServer"];
string database = ["DatabaseName"];

For the database connection string in the connectionStrings node, if configured as follows:

<connectionStrings>
    <add name="MyDbConnection" 
         connectionString="Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword" 
         providerName="" />
</connectionStrings>

Then read in the code using the following method:

using ;
using ;
string connectionString = ["MyDbConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Perform database operations}

In addition, in the Core project, configuration information can also be obtained through dependency injection. First, configure the service in the file:

using ;
using ;
public void ConfigureServices(IServiceCollection services)
{
    var config = new ConfigurationBuilder()
       .SetBasePath(())
       .AddJsonFile("", optional: false, reloadOnChange: true)
       .Build();
    <IConfiguration>(config);
}

Then, in the class that needs to use configuration information, inject IConfiguration through the constructor:

public class MyService
{
    private readonly IConfiguration _config;
    public MyService(IConfiguration config)
    {
        _config = config;
    }
    public void DoSomething()
    {
        string value = _config["SomeSetting"];
    }
}

5.2 Update configuration files (operate with caution)

Although updating configuration files at runtime is feasible, be sure to do it with caution, as this operation may cause instability in the application. In traditional C# projects, you can use methods to update or file. For example, update the AppName configuration value in the appSettings node:

using ;
Configuration config = ();
["AppName"].Value = "New App Name";
();
("appSettings");

In the above code, first open the configuration file, then modify the value of the specified configuration item, then save the changes, and refresh the appSettings section so that the modified configuration can take effect immediately.

In a Core project, the configuration files are updated slightly differently. Assuming the configuration file is, to update the configuration value, you can use the following steps:

using ;
using ;
using ;
var config = new ConfigurationBuilder()
  .SetBasePath(())
  .AddJsonFile("", optional: false, reloadOnChange: true)
  .Build();
var appSettingsSection = ("AppSettings");
appSettingsSection["SomeSetting"] = "New Value";
var jsonConfig = (());
("", jsonConfig);

In this process, first build the configuration object, obtain the configuration section that needs to be updated, and after modifying the configuration value, reserialize the configuration object to JSON format and write it back to the configuration file. However, in practical applications, especially in production environments, this operation of updating configuration files directly at runtime should be fully tested and evaluated to avoid adverse effects on the normal operation of the application.

6. Expand other advanced configuration options

6.1 Custom Configuration Section

In actual project development, sometimes existing standard configuration nodes cannot meet complex business needs, and the custom configuration section comes in handy. The Custom Configuration Section allows us to flexibly define and organize configuration information according to the specific needs of the project.

The implementation of custom configuration section is mainly divided into two key steps. First, you need to write a configuration section processor class. This class must be inherited from the ConfigurationSection class, which defines the configuration properties we need. For example, we create a class that manages system user permission configuration:

using ;
public class UserPermissionsSection : ConfigurationSection
{
    [ConfigurationProperty("adminPermissions", IsRequired = true)]
    public string AdminPermissions
    {
        get { return (string)this["adminPermissions"]; }
        set { this["adminPermissions"] = value; }
    }
    [ConfigurationProperty("userPermissions", IsRequired = true)]
    public string UserPermissions
    {
        get { return (string)this["userPermissions"]; }
        set { this["userPermissions"] = value; }
    }
}

In the above code, the UserPermissionsSection class defines two properties adminPermissions and userPermissions, which are used to store permission information for administrators and ordinary users. The ConfigurationProperty feature is used to specify the relevant configuration of the attribute, such as whether it is a required attribute, etc.

Next, declare this custom configuration section in or file. Add the following content to the node of the file:

<configSections>
    <section name="userPermissions" type=", AssemblyName" />
</configSections>

The name attribute here specifies the name used when referring to the configuration section in the configuration file, and the type attribute specifies the complete namespace and assembly name of the configuration section processor class. Then, add the specific configuration of the custom configuration section under the node:

<userPermissions>
    <adminPermissions>FullAccess</adminPermissions>
    <userPermissions>LimitedAccess</userPermissions>
</userPermissions>

In this way, the information of the custom configuration section can be obtained through methods in the code and processed accordingly. For example:

UserPermissionsSection userPermissions = (UserPermissionsSection)("userPermissions");
string adminPermissions = ;
string userPermissionsValue = ;

6.2 Encrypt configuration file sensitive information

In today's data security-focused environment, sensitive information in configuration files, such as database connection strings, API keys, etc., may pose serious security risks to the application once leaked. Therefore, it is particularly important to encrypt some or all of the contents in the configuration file.

In C#, you can use the aspnet_regiis.exe tool to implement the encryption of configuration files. Taking the node in the encrypted file as an example, in the command prompt, switch to the corresponding version directory of the .NET Framework (for example, C:\Windows[]()\Framework\v4.8.04084), and then execute the following command:

aspnet_regiis -pe "connectionStrings" -app "/YourApplicationName" -prov "DataProtectionConfigurationProvider"

In the above command, -pe represents the encryption operation, "connectionStrings" specifies the name of the node to be encrypted, -app specifies the virtual path of the application, and -prov specifies the encryption provider. After executing this command, the node content in the file will be encrypted, and the encrypted content will be similar to the following:

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
        <CipherData>
            <CipherValue>...</CipherValue>
        </CipherData>
    </EncryptedData>
</connectionStrings>

When the application runs, .NET automatically decrypts the encrypted content using the specified encryption provider, and developers can get the connection string as usual by getting the connection string without writing additional decryption code in the code.

If you need to encrypt the file, since the aspnet_regiis.exe tool is mainly aimed at, you can first rename it, perform the encryption operation and then change it back to the original name. At the same time, in practical applications, the encryption key should be properly kept to avoid the loss of encryption due to the loss of key leakage. For example, the key can be stored in a secure server configuration that can only be accessed by an authorized system administrator.

7. Summary and review

During this journey of exploring C# configuration files, we have gained a deep understanding of many mysteries of . From their basic definition, creation and configuration methods, to the analysis of key nodes, to reading, updating, and advanced custom configuration sections and encrypting sensitive information, each step provides strong support for us to flexibly manage configurations in C# application development.

These two configuration files are like right-hand assistants in development, allowing us to easily deal with various configuration needs, whether it is simple application settings, complex database connections, security configurations, etc. I hope that in future C# development projects, everyone can skillfully apply this knowledge, and cleverly configure and lay a solid foundation for creating efficient, stable and secure applications according to the actual needs of the project. Let us create better software works with the help of configuration files in the world of code.

This is all about this article about C# configuration files and . For more related C# and content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!