How to read values from config.json in Console Application

瘦欲@ 提交于 2019-12-03 13:59:46

Have a type like the following:

public class FolderSettings
{
    public Dictionary<string, string> TargetFolderLocations { get; set; }
}

You can then use the ConfigurationBinder to automatically bind configuration sections to types like above. Example:

var folderSettings = ConfigurationBinder.Bind<FolderSettings>(config.GetConfigurationSection("Data"));
var path = folderSettings.TargetFolderLocations["TestFolder1"];

I've managed to solve it like this:

public class Program
{
    public IConfiguration Configuration { get; set; }
    public Dictionary<string,string> Paths { get; set; } 
    public Program(IApplicationEnvironment app,
           IRuntimeEnvironment runtime,
           IRuntimeOptions options)
    {
        Paths = new Dictionary<string, string>();
        Configuration = new ConfigurationBuilder()
            .AddJsonFile(Path.Combine(app.ApplicationBasePath, "config.json"))
            .AddEnvironmentVariables()
            .Build();
    }

    public void Main(string[] args)
    {
        var pathKeys = Configuration.GetConfigurationSections("TargetFolderLocations");
        foreach (var pathItem in pathKeys)
        {
            var tmp = Configuration.Get($"TargetFolderLocations:{pathItem.Key}");
            Paths.Add(pathItem.Key, tmp);
        }

        return;
    }

The way you've worded your question, your config.json file is at the root of the project, but you're looking in the executable directory at runtime. Assuming you're doing this from Visual Studio, and assuming you're not copying the config file in at build time, Environment.CurrentDirectory is probably bin\Debug, and the file is not there.

You can set the properties of config.json to Copy always from Solution Explorer, to ensure the file gets there.

You can use JavascriptSerializer (namespace: System.Web.Extension) to parse json into dictionary and find any value based on its key from json. You code would become:

 string json = System.IO.File.ReadAllText("PathToJsonFile");
 JavaScriptSerializer serializer = new JavaScriptSerializer();
 Dictionary<string, object> dic = serializer.Deserialize<Dictionary<string, object>>(json);

If you iterate over the dictionary, you can see all the keys and get their values using dic.

* Just an alternate solution *

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!