Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SetBasePath in ConfigurationBuilder in Core 2.0

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.

like image 506
Padhraic Avatar asked Oct 15 '22 22:10

Padhraic


1 Answers

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.

like image 411
Set Avatar answered Oct 17 '22 11:10

Set