繁体   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