Assembly.GetManifestResourceStream始终返回null

Asi*_*ood 3 c# resources .net-assembly asp.net-mvc-5

每当我完成任务时,它总是让我感到困惑Path-Resolution.我有关于报告问题的以下信息:

  • 运用 ASP.NET MVC-5 Application
  • 试图通过下面的代码访问font fileieMyriadPro-SemiBold.ttf
//a value receives a path + name of the file in variable i.e. name
string name = "myApplicationName.fonts.MyriadPro-Semibold.ttf";

//object (named as assembly) of class System.Reflection.Assembly. 
var assembly = Assembly.GetExecutingAssembly();

using (Stream stream = assembly.GetManifestResourceStream(name))
// stream always gets null value (don't know why!)
{
    if(stream != null)
    {
        //myCode waiting for above stream not to be null :-(
    }
    else
    {
        throw new ArgumentException("No resource with name " + name);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不太了解Visual Studio在不同类型的应用程序中的工作方式paths.

Que*_*ger 9

您的资源应该嵌入:

在此输入图像描述

您可以进行一些测试以获取所有资源并找到好名字.之后你的代码似乎是正确的.

 var allRessources= System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

 var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("fullpath here");
 if (stream == null) return;
Run Code Online (Sandbox Code Playgroud)

编辑

要在VS项目中添加文件作为嵌入式资源:只需将文件添加到项目中,单击它,然后在" 属性设置构建操作嵌入式资源"下.就是这样!

有关嵌入式资源的更多信息:https://support.microsoft.com/en-us/kb/319292#bookmark-4

  • 是的,我认为您的资源不是嵌入式的.如果您使用的是visual studio,只需将文件添加到项目中,单击它,然后在**Properties**set**Build Action**下**嵌入资源**.就是这样! (2认同)