首页 > 解决方案 > 如何在.net core的库中包含文件

问题描述

我有项目 A,它依赖于项目 B。

在项目 BI 中,我在构建中包含其他文件,如下所示:

<ItemGroup>
    <None Include="jsfiles/**/*"  CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

在项目 B 中,我正在加载这样的文件:

File.ReadAllText("jsfiles/foo.js");

这会将文件成功复制到 out 目录中。但是当我在项目 A 中包含项目 B 时,运行时正在解析相对于项目 A 的根目录而不是输出目录的文件。因为文件不存在于项目 A 的根目录中(但它们确实存在于项目 A 的输出目录中),所以找不到它们。

什么是在项目 B 中加载文件的正确方法,以便在项目 B 包含在项目 A 中时它仍然可以工作?

基本上,我只是在寻找在项目中包含额外资源的正确方法。

标签: c#.net.net-core

解决方案


我们的解决方案层次结构:

ProjectA
  Startup.cs       // Uses TextService.cs that uses Text.txt
  ProjectA.csproj  // Does not want to now anything about how TextService works
                   // just has a dependency on Project B
ProjectB
  Text.txt
  TextService.cs   // This one uses Text.txt file
  ProjectB.csproj  // Contains EmbeddedResource with Text.txt here

您的用例可能会有所不同,但我发现对我们有用的是在文件中使用EmbeddedResource而不是Content标记。csproj这样,文件就会包含在上述两种情况中:

  • 建的时候ProjectB
  • 发布时ProjectA(具有ProjectB依赖项)

中的代码块ProjectB.csproj

<ItemGroup>
  <EmbeddedResource Include="path\to\Text.txt">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </EmbeddedResource>
</ItemGroup>

或者,这可以在 Visual Studio(2019 年测试)中通过转到txt文件的属性并设置Build Action: Embedded resource.


推荐阅读