User Configuration Settings in .NET Core

2020-06-12 03:47发布

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?

1条回答
霸刀☆藐视天下
2楼-- · 2020-06-12 03:58

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; }
    }
}
查看更多
登录 后发表回答