简体   繁体   English

如何从控制台应用程序中的config.json读取值

[英]How to read values from config.json in Console Application

I just installed ASP.NET 5 and created a Console Application in Visual Studio. 我刚安装了ASP.NET 5并在Visual Studio中创建了一个控制台应用程序。 I've added a file, config.json, to the root folder of the project. 我已经将一个文件config.json添加到项目的根文件夹中。

It looks like this: 它看起来像这样:

{
    "Data": {
        "TargetFolderLocations": {
            "TestFolder1": "Some path",
            "TestFolder2": "Another path"
        }
    }
}

My Program.cs looks like this 我的Program.cs看起来像这样

public void Main(string[] args)
{
    var configurationBuilder = new ConfigurationBuilder(Environment.CurrentDirectory)
    .AddJsonFile("config.json")
    .AddEnvironmentVariables();
    Configuration = configurationBuilder.Build();

    //Doesn't work...null all the time
    var test = Configuration.Get("Data:TargetFolderLocations");

    Console.ReadLine();
}

How can I access the TargetFolderLocations key with code? 如何使用代码访问TargetFolderLocations键?

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

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. 然后,您可以使用ConfigurationBinder自动将配置节绑定到上面的类型。 Example: 例:

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

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. 你的问题的方式,你的config.json文件是项目的根目录,但你在运行时查看可执行文件目录。 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. 假设您是从Visual Studio执行此操作,并假设您没有在构建时复制配置文件, Environment.CurrentDirectory可能是bin\\Debug ,并且该文件不在那里。

You can set the properties of config.json to Copy always from Solution Explorer, to ensure the file gets there. 您可以将config.json的属性设置为Copy always从解决方案资源管理器Copy always ,以确保文件到达那里。

You can use JavascriptSerializer (namespace: System.Web.Extension) to parse json into dictionary and find any value based on its key from json. 您可以使用JavascriptSerializer(namespace:System.Web.Extension)将json解析为字典,并根据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. 如果迭代字典,您可以看到所有键并使用dic获取​​它们的值。

* Just an alternate solution * *只是一个替代解决方案*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM