【问题标题】:Upgraded to VS 2017 15.6.0 and now Directory.GetCurrentDirectory() returns \bin\Debug\netcoreapp2.0升级到 VS 2017 15.6.0,现在 Directory.GetCurrentDirectory() 返回 \bin\Debug\netcoreapp2.0
【发布时间】:2018-03-08 16:03:52
【问题描述】:

升级后,我的所有 .net 核心控制台应用程序在调试时似乎都进入了错误的路径。

我有以下代码

private static void ConfigureServices(IServiceCollection serviceCollection)
{
        // build configuration
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())               
            .AddJsonFile("appsettings.json", false)
            .Build();
}

这可以正常工作,但现在我升级了,我收到以下错误

System.IO.FileNotFoundException: 'The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'D:\projects\myproject\bin\Debug\netcoreapp2.0\appsettings.json'.'

我知道我可以将 appsettings.json 复制到此路径,但我以前从未这样做过,而且在升级之前完全没问题。

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-2.0


    【解决方案1】:

    将 appsettings.json 文件属性“复制到输出目录”更改为“复制 al” appsettings.json 文件的“复制到输出目录”属性也应设置为“如果较新则复制”,以便应用程序能够访问它。

    【讨论】:

      【解决方案2】:

      我建议完全删除 .SetBasePath(Directory.GetCurrentDirectory()) 行。 SetBasePath 方法现在是可选的,如果不调用,then we infer the base path from application base

      关于您的错误。 There was a fix 在 dotnet 中,改变行为:

      将默认工作目录更改为输出文件夹而不是项目根目录。

      看起来你已经安装了最新版本的 .NET Core SDK。所以你现在需要将 appsettings.json 复制到输出文件夹。

      【讨论】:

      • 删除该行后仍然出现相同的错误,升级中发生了一些事情,现在在调试模式下运行项目时默认查看错误的路径
      • 这仍然是必需的.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)) ,当应用程序按照我假设的时间表运行时(我一直在使用它,似乎需要它)
      • 好吧,如果他们更新了那我想这回答了我的问题
      • 如果您不想复制资源或摆弄路径,那么在项目的调试页面上将工作目录更改为 .\ 可能是另一种选择。
      【解决方案3】:

      试试这个:

      string Path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\"));

      只需从 bin 中向上移动两个目录。

      【讨论】:

        【解决方案4】:

        Startup 从 1.x 到 2.0 略有变化,您不再使用配置生成器,它主要在幕后完成,但您可以在 Program.cs 中声明您的 appsettings.json 文件

        这里是操作方法:https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers

        【讨论】:

        • 这可能适用于 asp.net 核心,但我认为它不适用于 .net 核心控制台
        • 我们确实使用ConfigurationBuilder。事实上,在 2.0 中,我们现在有内置实现,在内部使用 ConfigurationBuilder 并不意味着您不能按需配置单独的配置源。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        • 2011-02-13
        • 2016-02-13
        • 1970-01-01
        • 2018-04-16
        • 1970-01-01
        相关资源
        最近更新 更多