簡體   English   中英

.NET Core應用程序在錯誤的文件夾中查找嵌入式文件

[英].NET Core app looks for embedded file in the wrong folder

我有一個在.NET 4.5.2上運行的ASP.NET Core應用程序。

該應用程序使用文件hello.json 我最初將其復制到build文件夾,如下所示:

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "copyToOutput": [ "hello.json" ]
  },

然后在編譯過程...\\bin\\Debug\\net452\\win7-x64\\文件復制到...\\bin\\Debug\\net452\\win7-x64\\

我運行MyApp.exe沒問題,但是如果我轉至...\\bin\\Debug\\net452\\並運行win7-x64\\MyApp.exe ,則在嘗試讀取文件時出現以下錯誤: System.IO.FileNotFoundException Could not find file '...\\bin\\Debug\\net452\\hello.json'.

我試圖將hello.json嵌入程序hello.json ,如下所示:

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "embed": [ "hello.json" ]
  }

但我得到了相同的結果。

如何使應用程序了解應該在.exe所在的位置查找文件,而不是在正在運行的位置查找文件?

事實證明,嵌入資源的結果是相同的,因為hello.json仍位於win7-x64\\文件夾中(該文件夾已由我先前的編譯復制到該文件夾​​中)。

您需要從程序集中獲取此文件,因此我對此進行了更改:

using (var reader = new StreamReader("hello.json", Encoding.UTF8))
{
    return reader.ReadToEnd();
}

對此:

Assembly executingAssembly = Assembly.GetExecutingAssembly();
Stream jsonStream = executingAssembly.GetManifestResourceStream("MyApp.hello.json");
using (var reader = new StreamReader(jsonStream, Encoding.UTF8))
{
    return reader.ReadToEnd();
}

參考: http : //codeopinion.com/asp-net-core-embedded-resource/ (注意:它使用JSON中的resource ,現已棄用,應將其替換為embed請參見問題中的project.json

您應該給json文件一個“內容”構建操作,不要手動將其復制到輸出文件夾

暫無
暫無

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

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