Using App.config Configuration in .NET Core
Developers accustomed to the System.Configuration library in .NET Framework may encounter issues when attempting to use it in .NET Core. This article provides a solution to this problem and explains how to parse app.config data in .NET Core applications.
Challenge
The use of app.config files and the System.Configuration library has been a common practice in .NET Framework applications. However, when porting code to .NET Core, developers may experience exceptions related to type loading and configuration initialization.
Solution
Despite the changes in the .NET Core architecture, it is possible to leverage app.config and System.Configuration with a few additional steps:
1. Create a .NET Standard 2.0 Library:
Establish a library project (.dll) targeting .NET Standard 2.0, which serves as a container for custom configuration sections.
2. Install System.Configuration.ConfigurationManager NuGet Package:
Install the System.Configuration.ConfigurationManager package (version 4.4.0) in your library project.
3. Define Custom Configuration Sections and Elements:
Create C# classes derived from ConfigurationSection (for sections) or ConfigurationElement (for elements) in your library project.
4. Create a .NET Core 2.0 Application:
Establish a .NET Core 2.0 application (.dll) that will interact with the app.config file and custom configuration sections.
5. Include App.config File:
Include an app.config file in your .NET Core application, ensuring it adheres to your custom configuration sections defined in the library project.
6. Access App.config Data in .NET Core:
Utilize the following code snippet in your .NET Core application to access app.config configuration data:
// Read a connection string from app.config string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString; // Read an app setting from app.config string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"];
Additional Considerations:
By following these steps, developers can effectively employ app.config and System.Configuration functionality in their .NET Core applications. This integration enables backward compatibility for existing configurations and preserves the familiar programming paradigm associated with .NET Framework applications.
The above is the detailed content of How Can I Use app.config and System.Configuration in My .NET Core Application?. For more information, please follow other related articles on the PHP Chinese website!