首页 > 解决方案 > 在 .net core 3.1 中保存 appsettings.json

问题描述

我想在我的 .net core 3.1 winforms 项目中有一个配置文件。我有以下工作来读取文件

using Microsoft.Extensions.Configuration;
using System;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace FeedRead
{

    public partial class Form1 : Form
    {

        private ConfigurationBuilder configuration;
        public Form1()
        {
            configuration = new ConfigurationBuilder();
            configuration.SetBasePath(System.IO.Directory.GetCurrentDirectory());
            configuration.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true);
            configuration.Build();
        }

但是当我进行更改后如何保存配置?

我尝试了以下但不知道如何完成它。

    private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
    {

        configuration.Properties.Add("col1Width", listView1.Columns[0].Width);
        var extn = configuration as Microsoft.Extensions.Configuration.IConfigurationBuilder; // not sure about
        var provider = extn.GetFileProvider();
        var info = provider.GetFileInfo(subpath: "appsettings.json"); // not sure about
        // how do i save?

    }

标签: c#.net-core

解决方案


有一个关于为什么它没有被添加的讨论。 在 GitHub 上

我问了一个有关绑定到配置的相关问题。

然后我使用以下内容来实现保存

  public static void SaveConfiguration(FeedReadConfiguration configuration)
    {
        var props = DictionaryFromType(configuration); 
        foreach (var prop in props)
        {
            SetAppSettingValue(prop.Key,prop.Value.ToString());
        }

    }

    private static Dictionary<string, object> DictionaryFromType(object atype)
    {
        if (atype == null) return new Dictionary<string, object>();
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        Dictionary<string, object> dict = new Dictionary<string, object>(); // reflection
        foreach (PropertyInfo prp in props)
        {
            object value = prp.GetValue(atype, new object[] { });
            dict.Add(prp.Name, value);
        }
        return dict;
    }

SetAppSettingsValue 来自这个问题

   public static void SetAppSettingValue(string key, string value, string appSettingsJsonFilePath = null)
    {
        if (appSettingsJsonFilePath == null)
        {
            appSettingsJsonFilePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "appsettings.json");
        }

        var json = System.IO.File.ReadAllText(appSettingsJsonFilePath);
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(json);

        jsonObj[key] = value;

        string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

        System.IO.File.WriteAllText(appSettingsJsonFilePath, output);
    }

推荐阅读