C# – When SetBasePath() and AddJsonFile() are missing for ConfigurationBuilder

If you’re trying to use ConfigurationBuilder to read appsettings.json, you probably have the following code snippet and are running into compiler errors:

using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .Build();
Code language: C# (cs)

This has three different errors, but the compiler only shows you one error at a time. This is due to the way this is designed – ConfigurationBuilder is in one library and its specialized functionality is provided by extension methods in other libraries. SetBasePath() and AddJsonFile() are extension methods in two different libraries.

If you try to solve one problem at a time, you’ll see the following sequence of errors:

ErrorPackage to install
ConfigurationBuilder could not be found. VS helpfully tells you which package to add for this problem.Microsoft.Extensions.Configuration
ConfigurationBuilder doesn’t contain a definition for SetBasePath()Microsoft.Extensions.Configuration.FileExtensions
ConfigurationBuilder doesn’t contain a definition for AddJsonFile()Microsoft.Extensions.Configuration.Json

Save yourself the trouble and solve all problems at once by installing the Microsoft.Extensions.Configuration.Json package (because it contains the other two packages!):

Install-Package Microsoft.Extensions.Configuration.Json
Code language: PowerShell (powershell)

Note: This is installing with the Package Manager Console (View > Other Windows > Package Manager Console).

It should be noted that you’ll encounter the same sort of “one error at a time” situation when you try to use any ConfigurationBuilder extension methods. Look for the most specific package to take care of as many problems at once, just like I showed above.

For example, if you’re using AddUserSecrets(), it’s sufficient to just add the Microsoft.Extensions.Configuration.UserSecrets package to get all packages needed instead of adding one at a time.

Leave a Comment