dynamic write and read from appsettings in .netcore class library

Viewed 1321

We have a class library which has appsettings.json file for configuration.We need to write data dynamically and read it.We searched for solution but we need startup.cs for it to implement whereas we don't have in class library.Please suggest some solution or easy way to achieve it.We are using .net core and a worker service where this class library is called.

1 Answers

We have a class library which has appsettings.json file for configuration.We need to write data dynamically and read it

If you'd like to dynamically read and write data from a json file within your class library, you can refer to the following code snippet.

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);
}

enter image description here

Related