Coder Perfect

In Core 2.0, how do you set the BasePath in ConfigurationBuilder?

Problem

In Core 2.0, how do I set the base path in ConfigurationBuilder?

I googled the question and found this, this from Microsoft documents, and the 2.0 docs online, but they appear to be using a version of Microsoft.Extension. The configuration is based on 1.0.0-beta8.

I’d like to read the appsettings. json. Is there a different method to accomplish it with 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 Microsoft.Extensions.Configuration, Microsoft.Extensions.Configuration has been added. Set also showed that I needed to add Microsoft.Extensions.Configuration to FileExtensions. To retrieve the AddJsonFile extension, type Json.

Asked by Padhraic

Solution #1

Config.FileExtensions defines the SetBasePath extension function.

The Microsoft.Extensions.Configuration.FileExtensions package must be referenced.

Add a reference to the Microsoft.Extensions.Configuration.Json package to resolve AddJsonFile.

Answered by Set

Solution #2

I’m using Visual Studio 2017 v15.5 to create a.NET Core 2 console app. After installing Microsoft.Extensions, as others have pointed out. Configuration Microsoft.Extensions had to be included. To make the AddJsonFile() method work, you’ll need to use Configuration.Json. I didn’t need to add Configuration.FileExtensions because this made the SetBasePath() call work. (Both with and without it, my code builds and runs.)

In addition, I had a call to AddEnvironmentVariables() that required the addition of Configuration. EnvironmentVariables. The following is my code:

  var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory()) // requires Microsoft.Extensions.Configuration.Json
                    .AddJsonFile("appsettings.json") // requires Microsoft.Extensions.Configuration.Json
                    .AddEnvironmentVariables(); // requires Microsoft.Extensions.Configuration.EnvironmentVariables
  Configuration = builder.Build();

Surprisingly, using Microsoft.Extensions was the only using sentence I required. Configuration.

Answered by Ed Graham

Solution #3

This will solve the problem if you use both ‘Microsoft.Extensions.Configuration’ and ‘Microsoft.Extensions.Configuration.Json’.

https://www.nuget.org/packages/Microsoft.Extensions.Configuration/ https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/

Here’s an example of a ‘ConnectionFactory’.

using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace DataAccess.Infrastructure
{
 public class ConnectionFactory : IConnectionFactory
 {
    public ConnectionFactory()
    {
        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        Configuration = builder.Build();
    }


    public IConfigurationRoot Configuration { get; }
    public IDbConnection GetConnection
    {
        get
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var conn = new SqlConnection(connectionString);
            conn.Open();
            return conn;
        }
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }


            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~ConnectionFactory() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
} }

Answered by Anish Manchappillil

Solution #4

If you still can’t retrieve the JSON content after adding the reference, try removing it.

Go to the JSON file’s properties (right-click on the JSON file > properties). “Copy to Output Directory” should be changed to “Copy Always.”

check screenshot

Answered by Darshan Jain

Post is based on https://stackoverflow.com/questions/46843367/how-to-setbasepath-in-configurationbuilder-in-core-2-0