When you need to convert an existing .NET Framework Console application to .NET Core, there’s one pending question that is kept being asked. Can you still use the System.Configuration and App.config (XML) configuration instead of using the new Appsettings.json file instead?
There’s always a need for a most robust configuration file and with JSON, it offers more flexibility and scalability but it doesn’t make sense to use it for a console application that only need to read one or two values as parameters from the *.config file.
As an example on this particular case, the console file just need a data of which file to look for based on a date.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /> </startup> <appSettings> <!-- Date value must be in mm/dd/yyyy format. --> <add key="Rundate" value="mm/dd/yyyy" /> </appSettings> </configuration>
Running a .NET Core console application can expedite the runtime which will improve the completion time of the batch job and also as it’s leaner it will have a lower operating cost. Moreover, .NET Core is the future of .NET so we’re future proofing the processor.
So how do we use the same App.config file for a .NET Core application?
Setup the System.Configuration
From your Visual Studio, open the Package Manager Console by going to Tools menu, then pick NuGet Package Manager. You will see the window open with the following initial message and PM> prompt.
Each package is licensed to you by its owner. NuGet is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may include dependencies which are governed by additional licenses. Follow the package source (feed) URL to determine any dependencies. Package Manager Console Host Version 220.127.116.1106 Type 'get-help NuGet' to see all available NuGet commands. PM>
If you check the nuget.org website for System.Configuration.ConfigurationManager, you can just copy the command line (just substitute the version number you want to use).
PM> Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Or if you want to use the latest, just click on the Copy button and paste it on your Package Manager Console window.
Once it’s installed, don’t forget to add using System.Configuration directive in your code.
Open App.config file and remove the
block so it will look like the following:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <!-- Date value must be in mm/dd/yyyy format. --> <add key="Rundate" value="mm/dd/yyyy" /> </appSettings> </configuration>
Test the program.
This is just a simple way to convert your existing .NET Framework console application to .NET CORE without complicating the existing configuration.