我正在使用官方文档中IOptions描述的模式.
当我从中读取值时appsetting.json,这可以正常工作,但是如何更新值并将更改保存回来appsetting.json?
在我的例子中,我有几个字段可以从用户界面编辑(由管理员用户在应用程序中).因此,我正在寻找通过选项访问器更新这些值的理想方法.
我的应用程序的Release文件夹中有一个settings.json文件.我想要做的是更改它的值,而不是暂时,永久..这意味着,删除旧条目,写一个新条目并保存它.
这是JSON文件的格式
{
"Admins":["234567"],
"ApiKey":"Text",
"mainLog": "syslog.log",
"UseSeparateProcesses": "false",
"AutoStartAllBots": "true",
"Bots": [
{
"Username":"BOT USERNAME",
"Password":"BOT PASSWORD",
"DisplayName":"TestBot",
"Backpack":"",
"ChatResponse":"Hi there bro",
"logFile": "TestBot.log",
"BotControlClass": "Text",
"MaximumTradeTime":180,
"MaximumActionGap":30,
"DisplayNamePrefix":"[AutomatedBot] ",
"TradePollingInterval":800,
"LogLevel":"Success",
"AutoStart": "true"
}
]
}
Run Code Online (Sandbox Code Playgroud)
假设我想更改密码值而不是BOT PASSWORD我希望它只是密码.我怎么做?
我想要我的 .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();
}
Run Code Online (Sandbox Code Playgroud)
但是当我进行更改后如何保存配置呢?
我尝试了以下操作,但不知道如何完成。
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
// …Run Code Online (Sandbox Code Playgroud)