How to read appSettings.json in .Net Core Console Application, use configuration files in .net core console

Read appSettings json in .Net Core Console Application

In this post I will share how to read configuration file data in .net core console application, like reading values from appSettings.json in .net core console application.

If you have some experience in working with asp.net core application, then you probably already know how to read appSettings.json in asp.net core application, but reading configuration values in .net core console application is done differently, that’s why this post.

How to read config values in .net core console application

Let's create a appsettings.json file in your application, and set some database configuration values like example below, this part is same as any other .net core application.

{
  "DbConnectionConfig": {
    "DatabaseName": "MyDBName001",
    "UserName": "myusername",
    "Password": "mpassword002",
    "ServerName": "SERVER0012\\SQLEXPRESS"
  }
}

Now to use configuration framework in our console application, we need to install following three libraries from nuget packages.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.FileExtensions;
using Microsoft.Extensions.Configuration.Json;

Connection is something will be used in multiple places, so we want to create reusable component, therefore, create a class file with name DbConnection (you can give any meaningful name as per your choice) and write following code.

We need to use ConfigurationBuilder to read values from any configuration file in .net core console application, becasue, like other .net core application, we don't have any startup file to configure configuration framework, so instead of using dependency injection, we need to use Build method of ConfigurationBuilder class to create a new instance.

static IConfiguration Config = new ConfigurationBuilder()
                .AddJsonFile(getRootPath("appSettings.json"))
                .Build();

As you can see, there is a mthod called getRootPath in above code, mapping any file in application root is something tricky, I didn’t find any built in method that can provide me the root value, so we need to write some additional code to get the application root path.

static string getRootPath(string rootFilename)
{
string _root;
var rootDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
Regex matchThepath = new Regex(@"(?<!fil)[A-Za-z]:\\+[\S\s]*?(?=\\+bin)");
    var appRoot = matchThepath.Match(rootDir).Value;
    _root= Path.Combine(appRoot, rootFilename);
            
    return _root; 
}

Ideally you should keep that method is a separate file or can create an extension method, which will make the method more usable, but here I have kept in the same file just to keep the post relevant to current topic.

Appsetting json file using configuration instance, here is how we can create a read only property in connection file , finally create a connection string using all proerties.

public static string DatabaseName
    {
        get
        {
            return Config.GetSection("DbConnectionConfig")["DatabaseName"];
        }
    }

Notice how the reading done, Config.GetSection("DbConnectionConfig")["DatabaseName"];, first retrieve the section you want to pick, and then specify the key name, like Config.GetSection("sectionName")["keyName"];

Hope you will able to use the same code example to read configuration values from appsetting.json in .net core console application

Here is the comple class code you can use in your application directly.

    
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Text.RegularExpressions;
namespace WebTrainingRoom
{
    public class DbConnection
    {
        
        static IConfiguration Config = new ConfigurationBuilder()
                .AddJsonFile(getRootPath("appSettings.json"))
                .Build();
       

        public static string DatabaseName
        {
            get
            {
                return Config.GetSection("DbConnectionConfig")["DatabaseName"];
            }
        }
        

        public static string UserName
        {
            get
            {
                return Config.GetSection("DbConnectionConfig")["UserName"];
            }
        }


        public static string Password
        {
            get
            {
                return Config.GetSection("DbConnectionConfig")["Password"];
            }
        }


        public static string ServerName
        {
            get
            {
                return Config.GetSection("DbConnectionConfig")["ServerName"];
            }
        }

        public static string ConnectionString
        {
            get
            {
                return ($"Server={ServerName};Database={DatabaseName};User ID={UserName};Password={Password};Trusted_Connection=False;MultipleActiveResultSets=true;");
            }
        }
         
    }
}

So to use the connection string in your application simply call the static property like DbConnection.ConnectionString, enjoy!

 
free C# tutorial online


c# .net core new features
Other Online Tutorial

C# .net Interview Questions Answers

.Net C# Examples | Join .Net C# Course