c# - 如何在.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 中时它仍然可以工作?
基本上,我只是在寻找在项目中包含额外资源的正确方法。
解决方案
我们的解决方案层次结构:
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
.
推荐阅读
- iis - 部署时的 Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery
- c++ - C++:关于方法和“已经有正文”错误的基本问题
- mongodb - Strapi 和 Netlify cms 之间的差异
- flask - Flask Session Cookie 不保存?
- angular - 访问存储可观察数组内容并对每个项目执行功能
- docker - Docker 无法在本地找到图像
- f# - 如何在 F# 中实现获取最大元素函数?
- youtube - 如何使用 youtube-dl 下载 1080p mp4 YouTube 视频?
- sql - 关于Oracle数据库格式列的一个简单问题
- go - 如何在不执行变量的情况下将函数分配给变量?