簡體   English   中英

升級到 VS 2017 15.6.0,現在 Directory.GetCurrentDirectory() 返回 \bin\Debug\netcoreapp2.0

[英]Upgraded to VS 2017 15.6.0 and now Directory.GetCurrentDirectory() returns \bin\Debug\netcoreapp2.0

升級后,似乎我所有的 .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 復制到這個路徑,但我以前從來沒有這樣做過,而且在升級之前它完全沒問題。

我建議完全刪除.SetBasePath(Directory.GetCurrentDirectory())行。 SetBasePath方法現在是可選的,如果未調用它,那么我們會從應用程序庫推斷基本路徑

關於你的錯誤。 dotnet 中有一個修復程序,它改變了行為:

將默認工作目錄更改為輸出文件夾而不是項目根目錄。

看起來你已經通過 VS 更新安裝了最新版本的 .NET Core SDK。 所以你現在需要將 appsettings.json 復制到輸出文件夾。

將 appsettings.json 文件屬性“復制到輸出目錄”更改為“復制”appsettings.json 文件“復制到輸出目錄”屬性也應設置為“如果更新則復制”,以便應用程序能夠訪問它.

Startup 從 1.x 到 2.0 發生了一些變化,您不再使用配置生成器,它主要是在幕后完成的,但是您可以在 Program.cs 中聲明您的appsettings.json文件

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

試試這個:

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

只需從 bin 中向上移動兩個目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM