How to read values from config.json in Console Application

后端 未结 4 2217
南旧
南旧 2021-02-15 08:54

I just installed ASP.NET 5 and created a Console Application in Visual Studio. I\'ve added a file, config.json, to the root folder of the project.

It looks like this:

4条回答
  •  失恋的感觉
    2021-02-15 09:39

    I've managed to solve it like this:

    public class Program
    {
        public IConfiguration Configuration { get; set; }
        public Dictionary Paths { get; set; } 
        public Program(IApplicationEnvironment app,
               IRuntimeEnvironment runtime,
               IRuntimeOptions options)
        {
            Paths = new Dictionary();
            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;
        }
    

提交回复
热议问题