如何获取引用NuGet包中contentFiles的文件流?
获取NuGet包中Content文件的Stream
针对你的场景,有两种可靠的方式获取这些文件的Stream,具体选择取决于你的需求:
方案一:将文件改为嵌入资源(推荐,无文件路径依赖)
原配置中把文件设为Content,虽然会打包进NuGet,但对于类库场景,依赖输出目录的文件路径容易出问题。更稳妥的方式是将这些模板文件改为嵌入资源,随程序集一起分发,直接从程序集中读取Stream。
修改Assembly A的项目配置
把Content节点替换为EmbeddedResource,并可选指定资源逻辑名称(方便后续精准读取):
<PropertyGroup> <AssemblyName>MyAssemblyNamespace.Reporting</AssemblyName> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="ReportTemplates/**/*.*"> <IncludeInPackage>true</IncludeInPackage> <!-- 指定资源逻辑名称,格式为「程序集命名空间 + 文件相对路径」,路径分隔符用点号 --> <LogicalName>MyAssemblyNamespace.Reporting.ReportTemplates.%(RecursiveDir)%(Filename)%(Extension)</LogicalName> </EmbeddedResource> </ItemGroup>
在Assembly B中读取Stream
通过程序集对象获取嵌入资源的Stream,注意资源名称要和配置中的LogicalName一致:
using System.Reflection; using System.IO; // 加载Assembly A的程序集 var reportingAssembly = Assembly.Load("MyAssemblyNamespace.Reporting"); // 替换为实际的资源名称,比如模板文件是ReportTemplates/Invoice.tpl var resourceName = "MyAssemblyNamespace.Reporting.ReportTemplates.Invoice.tpl"; // 获取Stream using Stream templateStream = reportingAssembly.GetManifestResourceStream(resourceName); if (templateStream != null) { // 这里处理Stream,比如读取内容 using var reader = new StreamReader(templateStream); string content = reader.ReadToEnd(); }
提示:如果不确定资源名称,可以调用
reportingAssembly.GetManifestResourceNames()输出所有嵌入资源的名称,找到对应文件的名称。
方案二:读取输出目录中的Content文件(保留原Content配置)
如果需要允许用户修改模板文件,可保留Content配置,确保文件被复制到Assembly B的输出目录后,直接读取文件流。
完善Assembly A的Content配置
添加CopyToOutputDirectory属性,确保文件会被复制到引用项目的输出目录:
<ItemGroup> <Content Include="ReportTemplates/**/*.*"> <IncludeInPackage>true</IncludeInPackage> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup>
在Assembly B中读取Stream
通过程序集输出目录拼接文件路径,读取本地文件流:
using System.Reflection; using System.IO; // 获取当前程序集的输出目录 string outputDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // 拼接模板文件路径 string templatePath = Path.Combine(outputDir, "ReportTemplates", "Invoice.tpl"); if (File.Exists(templatePath)) { using Stream templateStream = File.OpenRead(templatePath); // 处理Stream }
方案对比
- 嵌入资源:无需依赖外部文件,资源随程序集分发,适合固定不变的模板文件。
- 输出目录文件:允许用户修改文件内容,但需确保部署时文件路径正确,适合需要可定制的场景。
内容的提问来源于stack exchange,提问作者clemensoe
相关产品推荐
相关产品推荐

