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.

In .net core console application we can have any type of configuration file, like appsettings.xml or appsettings.json, but we must map the file with configuration framework, so we can retrieve and use those configuration values anywhere in application using dependency injection in console application.

there are different ways we can configure the file we want with configuration framework, one easy method is ConfigureAppConfiguration method with host builder.

public static IHostBuilder CreateHostBuilder(string[] args)
{
   var _dirRoot= System.AppContext.BaseDirectory;
	int _binIndex=_dirRoot.IndexOf("\\bin");
	_dirRoot= _dirRoot.Remove(_binIndex);
	 var _hostBuilder = Host.CreateDefaultBuilder(args)              
	 .ConfigureServices((services) =>
	 {                 
		 services.AddSingleton<DbService>();
		 services.AddLogging();                 
	 })
	 .ConfigureAppConfiguration(app =>
	  {
		  app.AddJsonFile($"{_dirRoot}\\appsettings.json");
	  });
	return _hostBuilder;
}

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.

Read configuration in 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();
How to get application root path in console app

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; 
}

There is another alternate way of getting the root path of console application in .net core.

var _dirRoot= System.AppContext.BaseDirectory;
int _binIndex=_dirRoot.IndexOf("\\bin");
_dirRoot= _dirRoot.Remove(_binIndex);

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!

 
se configuration file in .net core console
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course