.Net Core 库中的嵌入式资源 [英] Embedded resource in .Net Core libraries

查看:63
本文介绍了.Net Core 库中的嵌入式资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究 .Net Core,我没有看到经典资源和任何看起来像资源的东西.例如,在经典的 .Net 类库中,我可以将带有一些脚本的文本过滤器添加到我的项目中,然后我可以将这些文件添加到项目的资源中.之后,我可以通过以下方式轻松使用它:

I just have started looking into .Net Core, and I don't see classical resources and anything what looks like resources. In classical .Net class libraries I was able to add, for example, text filtes with some script to my project, than I can add these files to project's resources. After that I could easily use that by the following way:

Connection.Execure(Properties.Resources.MySuperScript);

我看到 .Net Core 库中没有这样的功能,至少我没有看到..Net Core 中是否有替代方法可以将一些静态数据作为嵌入式资源存储在库中?如果存在,如何使用它?

I see that there isn't such feature in .Net Core libraries, at least I don't see. Is there an alternative in .Net Core to store some statical data as an embedded resource in libraries? And how to use that if it exists?

推荐答案

更新:

.NET Core 1.1 及更高版本已删除 project.json 并返回到 .csproj 文件.这改变了第 2 步,但并没有那么大.必要的行非常相似:

.NET Core 1.1 and later have dropped project.json and returned to .csproj files. This changes Step 2, but not all that much. The necessary lines are very similar:

<ItemGroup>
  <Content Remove="_fonts/OpenSans.ttf" />
  <Content Remove="_fonts/OpenSans-Bold.ttf" />
  <Content Remove="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>
<ItemGroup>
  <EmbeddedResource Include="_fonts/OpenSans.ttf" />
  <EmbeddedResource Include="_fonts/OpenSans-Bold.ttf" />
  <EmbeddedResource Include="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>

可能有类似的*.tff形式;未经证实.

There may be a similar *.tff form; unconfirmed.

第 1 步和第 3 步保持不变.

Steps 1 and 3 are unchanged.

要在 .NET Core 1.0 项目中使用嵌入式资源,请执行以下操作:

To use embedded resources in .NET Core 1.0 project do the following:

  1. 像往常一样添加嵌入的文件.

  1. Add your embedded file(s) as usual.

示例:名为_fonts"的目录中的一些字体文件

Example: some FONT files on a directory named "_fonts"

修改project.json"以包含相关资源.

Modify "project.json" to include the related resources.

就我而言:

 "buildOptions": {
    "embed": {
      "include": [
        "_fonts/*.ttf"    
      ]
    } 
  },

  • 在代码中访问嵌入的资源.

  • Access the embedded resource in code.

    var assembly = typeof(MyLibrary.MyClass).GetTypeInfo().Assembly;
    Stream resource = assembly.GetManifestResourceStream("MyLibrary._fonts.OpenSans.ttf");
    

    关键是在上使用正确的名称GetManifestResourceStream 调用.您必须使用 [程序集名称].[目录].[文件名].

    这篇关于.Net Core 库中的嵌入式资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆