9/29/2022 12:57:44 AM

If you run a .NET Core Console App, you can store settings in an appsettings.json file. It is very easy to get the values out of this file and populate a class object. It is, of course, only very easy if you know how to do it and for some reason, I find Microsoft does not like showing you the easy way to do something. They do like to talk DI and interfaces though (just like a bunch of nerds over at Stack Overflow - less opinions, more answers). People just want the fuckin answer. Hopefully the following code provides the fuckin answer.

You can copy the code below to your Pogram.cs file. The steps to make the code work are in the comments.


using Microsoft.Extensions.Configuration;

namespace TestApp
{
    internal class Program
    {
        class Settings
        {
            public string DatabaseName { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
        }


        static void Main(string[] args)
        {
            //add Nuget Packages
            // Microsoft.Extensions.Configuration
            // Microsoft.Extensions.Configuration.Binder
            // Microsoft.Extensions.Configuration.Json            
            
			// add using statement
            // using Microsoft.Extensions.Configuration;



            //add appsettings.json file to root of project            
			
			//add contect to appsettings.json
			//
            //  {
            //    "Settings": {
            //        "DatabaseName": "My Db Name",
            //        "Username": "My Username",
            //        "Password": "My Password"
            //    }
            //  }
			
			//On file properties (press F4 to open the properties window), Set "Copy to Output Directory" = "Copy always"            


            var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                //.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            var config = configuration.Build();

            var settings = config.GetSection("Settings").Get();


			//you should now have a Settings object filled with the values in the appsettings.json file
			//write some awesome code
        }
    }
}