'How to read appsetting.json or App.config using class library? both json and config file are in same class library project

So here is the scenario.

I am developing some independent tool so i am working with class library. Now i want to save some information into same project which is class library. I tried with appsetting.json and App.config but it only works in web project.

My project looks like below

enter image description here

i tried below code

var id = System.Configuration.ConfigurationManager.AppSettings["client_id"];

but it is not working. if i put that same file in web project it is reading successfully.

In my case config/json file must be in class library and must read from itself



Solution 1:[1]

I found a soultion to this problem.

You can add Resource.resx from property window of class library.

here are the screen shots.

enter image description here

and then use code as below

using AdobeSign.Properties;

var id = Resources.client_id.ToString();

Solution 2:[2]

If you want to have config.json in your class library separately, I recommend that you define your configuration model and implement deserialization for the file.

let's just assume your config.json content is like,

{ "MyValue1": "Hello", "MyValue2": "World" }

you can define Configuration class like below,

using Newtonsoft.Json;
using System;
using System.IO;

namespace Example
{
    public class Configuration
    {
        public string MyValue1 { get; set; }
        public string MyValue2 { get; set; }

        public static Configuration Load(string path)
        {
            if (File.Exists(path))
            {
                var json = File.ReadAllText(path);
                return JsonConvert.DeserializeObject<Configuration>(json);
            }
            else
            {
                throw new Exception("Configuration file not found!");
            }
        }
    }
}

then you can load your config object from the file and use it like below,

var config = Configuration.Load(Path.Combine(Directory.GetCurrentDirectory(), "config.json"));
Console.Write(config.MyValue1);
Console.Write(config.MyValue2);

Solution 3:[3]

In a .net core application you need to use Dependency Injection to inject IConfiguration into your class which will expose your appsettings json values:

public class Foo
{
    private IConfiguration _config { get; set; }
    public Foo(IConfiguration config)
    {
        this._config = config;
    }
}

Now you can read settings:

    public void DoBar()
    {
        var id = _config.GetSection("client_id").Value;
    }

Just keep chaining .GetSection() to move down your hierarchy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aijaz Chauhan
Solution 2 ByungYong Kang
Solution 3 Dharman