繁体   English   中英

如何使用 c# 获取或设置自定义 appsetting.json

[英]how can I get or set custom appsetting.json with c#

[{
    "Group": " ",
    "Key": "Sender:StoreType",
    "Value": "ExchangeStack.Stores.Rabbit.RabbitStore,ExchangeStack.Stores.Rabbit",
    "Description": "存储器(发送) 不用改"
}, {
    "Group": " ",
    "Key": "Receiver:StoreType",
    "Value": "ExchangeStack.Stores.Rabbit.RabbitStore,ExchangeStack.Stores.Rabbit",
    "Description": "存储器(接收)不用改"
}, {
    "Group": " ",
    "Key": "Sender:BatchSize",
    "Value": 1000,
    "Description": "一次发送的数量"
}]

如何通过键的值获取或设置描述(或值)的值? 配置文件格式由其他程序生成并且已经在运行,我无法更改其结构。

假设,您有一个 class,它代表您的配置:

public class MyConfig
{
    public string Group { get; set; }
    public string Key { get; set; }
    public string Value { get; set; }
    public string Description { get; set; }
}

让我们进一步假设,您的MyConfig数组存储在您的 appsettings.json 中,如下所示:

{
    "MyConfig": [
        {
            "Group": " ",
            "Key": "Sender:StoreType",
            "Value": "ExchangeStack.Stores.Rabbit.RabbitStore,ExchangeStack.Stores.Rabbit",
            "Description": "存储器(发送) 不用改"
        },
        { ... }
    ]
}

你可以像这样得到你的价值观:

var builder = new ConfigurationBuilder()
    .AddJsonFile($"appsettings.json", true, true)
    .AddEnvironmentVariables();
var config = builder.Build();
//Get the section
var cfg = config.GetSection("MyConfig")
//and bind it to your strongly typed object
                .Get<MyConfig[]>();
//iterate over it
foreach(var item in cfg) {
    Console.WriteLine($"{item.Key} --- {item.Value}");
}

Output:

Sender:StoreType --- ExchangeStack.Stores.Rabbit.RabbitStore,ExchangeStack.Stores.Rabbit
Receiver:StoreType --- ExchangeStack.Stores.Rabbit.RabbitStore,ExchangeStack.Stores.Rabbit
Sender:BatchSize --- 1000

至于你的问题,写回设置:你可以简单地用cfg[0].Value覆盖设置,但这只会更新你的配置的 memory 表示,而不是文件本身。 如果您愿意,您当然可以自己将其写入 json 文件,但我建议您将配置存储在某种数据库中,并为此插入您自己的配置提供程序,因为它会使读取和回写如果您向外扩展,您的更改会更容易、更集中。

        string targetDir = Environment.CurrentDirectory + "\\AppSetting.json";
        string jsonString = File.ReadAllText(targetDir, Encoding.Default);
        jsonString = "{\"MyConfig\":" + jsonString.Replace("\r\n", "") + "}";
        IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(jsonString))).AddEnvironmentVariables();
        IConfigurationRoot config = builder.Build();
        MyConfig[] cfg = config.GetSection("MyConfig").Get<MyConfig[]>();

谢谢你@Marco

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM