How to SetBasePath in ConfigurationBuilder in Core 2.0

Padhraic picture Padhraic · Oct 20, 2017 · Viewed 81.7k times · Source

How can I set the base path in ConfigurationBuilder in Core 2.0.

I have googled and found this question, this from Microsoft docs, and the 2.0 docs online but they seem to be using a version of Microsoft.Extension.Configuration from 1.0.0-beta8.

I want to read appsettings.json. Is there a new way of doing this in Core 2.0?

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp2
{
    class Program
    {
        public static IConfigurationRoot Configuration { get; set; }

        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) // <== compile failing here
                .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            Console.WriteLine(Configuration.GetConnectionString("con"));
            Console.WriteLine("Press a key...");
            Console.ReadKey();
        }
    }
}

appsetting.json

{
  "ConnectionStrings": {
    "con": "connection string"
  }
}

UPDATE: In addition to adding Microsoft.Extensions.Configuration.FileExtensions as indicated below by Set I also needed to add Microsoft.Extensions.Configuration.Json to get the AddJsonFile extension.

Answer

Set picture Set · Oct 20, 2017

The SetBasePath extension method is defined in Config.FileExtensions.

You need to add a reference to the Microsoft.Extensions.Configuration.FileExtensions package.

To resolve AddJsonFile, add a reference to the Microsoft.Extensions.Configuration.Json package.