When you create a new Blazor project, you get an appsettings.json file in the structure to get the settings conatined therein at startup. How do you implement it for a .NET Core Console app?

There is a good reference on this Adding AppSettings.json Configuration to a .NET Core Console Application, Whist I found it did not work completely as specified, I was able to so with some tweeking.

The appseetting.json file

{
  "PathToRepository": "C:\\Users\\me\\Downloads\\azure-iot-samples-csharp-master_src\\azure-iot-samples-csharp-master",
  "PathToRepositoryAlt": "\\Users\\me\\source\\dotnet-iot\\iot",

}

Code to access it

string DefaultPath = Configuration.GetValue<string>("PathToRepository");
string DefaultPathAlt = Configuration.GetValue<string>("PathToRepositoryAlt");

Using Declaration

using Microsoft.Extensions.Configuration;

Packages to include

Get them via Nuget

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="3.1.6" />
</ItemGroup>

Note not all of these packages are required for the functionality demonstrated here.

The Scaffolding at the start of the appp

    var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    Microsoft.Extensions.Configuration.IConfiguration Configuration = builder.Build();

 TopicSubtopic
   
 This Category Links 
Category:Coding Index:Coding
  Next: > .NET Core
<  Prev:   Blazor