c# - 在 .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?
}
解决方案
有一个关于为什么它没有被添加的讨论。 在 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);
}
推荐阅读
- php - 如何将 topic_id 放入 Laravel 的产品表中
- arrays - 是否有用户定义的类型保护来要求数组中的元素?
- jenkins - 在 github 中推送项目时运行 pipline
- apache-flink - 四个 Flink Table API/SQL 数据类型包之间有什么关系?
- git - git push 卡住并编辑一个文件并添加提交但上传所有文件
- python - Pandas - 从 groupby 操作的前 n 组创建一个新的 DataFrame
- python - 我应该在哪里粘贴 get() 方法以在 Python Tkinter 中打印 entryBox 的值?
- android - 无法销毁活动
- python - 从残差函数中找到最优值
- css - 在 rails6 开发中禁用加载所有样式表