Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .settings files in .NET core?

I'm porting an application to .NET core which relies on a .settings file. Unfortunately, I can't find a way to read it from .NET core. Normally, adding the following lines to the .csproj would generate a TestSettings class that would let me read the settings.

<ItemGroup>
    <None Include="TestSettings.settings">
        <Generator>SettingsSingleFileGenerator</Generator>
    </None>
</ItemGroup>

Unfortunately, this no longer seems to do anything. I can't even verify that the SettingsSingleFileGenerator runs at all. This GitHub issue suggests that this is a bug with the new .csproj format, but no one has offered an alternative.

What is the proper way of reading .settings files in .NET core?

like image 804
Alex Reinking Avatar asked Feb 19 '18 00:02

Alex Reinking


1 Answers

For .NET Core 2.x, use the Microsoft.Extensions.Configuration namespace (see note below), and there are tons of extensions on NuGet you'll want to grab for reading from sources ranging from environment variables to Azure Key Vault (but more realistically, JSON files, XML, etc).

Here's an example from a console program that retrieves settings the same way we use them when Kestrel starts up for our Azure sites:

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

    // This allows us to set a system environment variable to Development
    // when running a compiled Release build on a local workstation, so we don't
    // have to alter our real production appsettings file for compiled-local-test.
    //.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)

    .AddEnvironmentVariables()
    //.AddAzureKeyVault()
    .Build();

Then in your code that needs settings, you just reference Configuration or you register IConfiguration for dependency injection or whatever.

Note: IConfiguration is read-only and will likely never get persistence per this comment. So if reading AND writing are required, you'll need a different option. Probably System.Configuration sans designer.

like image 132
McGuireV10 Avatar answered Oct 13 '22 01:10

McGuireV10