Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Configuration Settings in .NET Core

I spent all day yesterday researching this and cannot find any reasonable solution.

I'm porting a .NET Framework project to .NET Core 2.0. The project used user settings (Properties.Settings.Default) to store certain information that persisted through each application launch. It could also update this information (e.g. user preference options).

My understanding is that is does not exist in .NET Core? So how is it possible to achieve this? The closest thing I could find was installing a few NuGet packages and using Microsoft.Extensions.Configuration, however, this is not even close to Properties.Settings.Default in the .NET Framework.

First, it requires a file (JSON, XML, what have you) to be in the running file's directory. This seems insane, especially in the case of secure information. In addition, I don't want to push a config file with the project when internal libraries of my project should be able to handle all of it, as it did with .NET Framework.

I realize there are Environment Variables, but I cannot get them to load in for the life of me. It honestly should be a simple process so I'm not sure if I'm missing something blatantly obvious. Here, in the Properties>Debug section of my library, there is a section called "Environment variables" which I have added two values in.

Environment Variable Example

My configuration object looks like so:

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

To access the variables, I have tried these ways:

Configuration.GetSection("SettingName").Value;
Configuration["SettingName"];
Environment.GetEnvironmentVariable("SettingName");

They all return empty.

Also, is there no way to save a property? I understand it was designed to be light weight, but surely there is a way to save?

I've tried:

Configuration["SettingName"] = "Value";
Environment.SetEnvironmentVariable("SettingName", "Value");

It seems to update the memory, but not the file itself, which leaves persistant settings useless.

How can I read and save user settings in a library, while having it all contained within that library?

like image 766
anon Avatar asked Jul 15 '18 19:07

anon


People also ask

What file is used to define configuration settings in .NET Core?

The machine. config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.

How do I add a config file to .NET Core console app?

In a . NET core console application Configuration can be added using the ConfigurationBuilder class. Additionally, support for configuring the application using a Json file, environmental variables, command line or using a custom configuration provider can also be added.

Can we use Web config in .NET Core?

The web. config file has also been replaced in ASP.NET Core. Configuration itself can now be configured, as part of the application startup procedure described in Startup.


1 Answers

I created a static class that the user could access anywhere if needed. This isn't perfect but it is strongly typed, and only creates when the accesses the default property.

I was going to use DI to put the config into the properties of each class, but in some cases I wanted to have the class in the constructor.

Use:

public MainWindow()
{
    InitializeComponent();

    var t = AppSettings.Default.Theme;
    AppSettings.Default.Theme += "b";
    AppSettings.Default.Save();
}

The class:

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TestClient
{

    public class AppSettings
    {
        private AppSettings()
        {
            // marked as private to prevent outside classes from creating new.
        }

        private static string _jsonSource;
        private static AppSettings _appSettings = null;
        public static AppSettings Default
        {
            get
            {
                if (_appSettings == null)
                {
                    var builder = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

                    _jsonSource = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}appsettings.json";

                    var config = builder.Build();
                    _appSettings = new AppSettings();
                    config.Bind(_appSettings);
                }

                return _appSettings;
            }
        }

        public void Save()
        {
            // open config file
            string json = JsonConvert.SerializeObject(_appSettings);

            //write string to file
            System.IO.File.WriteAllText(_jsonSource, json);
        }

        public string Theme { get; set; }
    }
}
like image 80
Ron Barone Avatar answered Sep 20 '22 01:09

Ron Barone