【问题标题】:How to read values from config.json in Console Application如何在控制台应用程序中从 config.json 读取值
【发布时间】:2015-08-07 20:13:18
【问题描述】:

我刚刚安装了 ASP.NET 5 并在 Visual Studio 中创建了一个控制台应用程序。我在项目的根文件夹中添加了一个文件 config.json。

看起来像这样:

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

我的 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();
}

如何使用代码访问 TargetFolderLocations 键?

【问题讨论】:

  • Data.TargetFolderLocations吗?
  • 不幸的是,也不适用于 .TargetFolderLocations...
  • 我已经解决了,请看我的回答:)

标签: c# console-application asp.net-core


【解决方案1】:

有如下类型:

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

然后您可以使用ConfigurationBinder 将配置部分自动绑定到上述类型。示例:

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

【讨论】:

  • 这真的很干净,我之前已经将它绑定到类型,但我认为语法发生了变化,我找不到任何文档...将尝试这个并接受它作为正确答案如果它有效!
【解决方案2】:

我已经设法解决了这个问题:

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

【讨论】:

  • 感谢 JOSEFtw。你需要初始化你的“路径”字典变量,否则你会得到一个 NULL 异常。
【解决方案3】:

按照您提出问题的方式,您的 config.json 文件位于项目的根目录中,但您正在运行时查看可执行目录。假设您从 Visual Studio 执行此操作,并且假设您没有在构建时复制配置文件,Environment.CurrentDirectory 可能是 bin\Debug,并且该文件不存在。

您可以在解决方案资源管理器中将config.json 的属性设置为Copy always,以确保文件到达那里。

【讨论】:

  • 现在已经不是这样了。在安装了 .NET Core 1.0 工具的 VS 2015 中,您不再拥有该选项。相反,将其添加到 project.json 中的“buildOptions”中:“copyToOutput”:[“config.json”]
  • @ScottRFrost 谢谢。终于让我的控制台应用程序运行起来了。
【解决方案4】:

您可以使用 JavascriptSerializer (namespace: System.Web.Extension) 将 json 解析为字典,并根据其 key 从 json 中查找任何值。你的代码会变成:

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

如果你遍历字典,你可以看到所有的键并使用 dic 获取它们的值。

* 只是一个替代解决方案 *

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 1970-01-01
    • 2012-01-24
    • 2014-05-18
    • 2022-08-02
    • 2023-04-03
    • 2018-04-06
    • 1970-01-01
    • 2015-08-17
    相关资源
    最近更新 更多