【问题标题】:dynamic write and read from appsettings in .netcore class library从 .net 核心类库中的 appsettings 动态写入和读取
【发布时间】:2020-10-19 20:51:18
【问题描述】:

我们有一个类库,其中包含用于配置的 appsettings.json 文件。我们需要动态写入数据并读取它。我们搜索了解决方案,但我们需要 startup.cs 来实现它,而我们在类库中没有.请提出一些解决方案或简单的方法来实现它。我们正在使用.net核心和调用这个类库的工作服务。

【问题讨论】:

    标签: c# asp.net-core .net-core configuration configuration-files


    【解决方案1】:

    我们有一个类库,其中有 appsettings.json 文件用于配置。我们需要动态写入数据并读取它

    如果你想从你的类库中的一个json文件动态读写数据,可以参考下面的代码sn-p。

    var _filepath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory), "appsettings_for_classlibrary.json");
    
    JObject o1 = JObject.Parse(System.IO.File.ReadAllText(_filepath));
    
    ((JValue)o1["Item1"][0]["Ival"]).Value = "test";
    
    o1.Add("NewItem", "Test Value");
    
    using (System.IO.StreamWriter file = System.IO.File.CreateText(_filepath))
    using (JsonTextWriter writer = new JsonTextWriter(file))
    {
        o1.WriteTo(writer);
    }
    

    【讨论】:

    • 请将 Build Action 设置为 content 并将 Copy to Output Directory 设置为 Copy always i> 或 如果较新则复制 用于该 json 文件,例如 this.
    • 嗨,韩,感谢您的回复。您的代码满足了我们的基本需求,例如读取和写入类库中的 json 文件。但是,我们希望写入 appsettings.json,我们希望使用 .net 核心中提供的配置。
    • we want to use configuration provided in .net core你好@Gani.one,如果你检查the definition of JsonConfigurationProvider,你会发现内置的JsonConfigurationProvider没有实现将数据保存到配置文件中。
    猜你喜欢
    • 2018-04-27
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多