c# - Assembly.GetManifestResourceStream 始终返回 null

标签 c# asp.net-mvc-5 resources .net-assembly

每当我处理Path-Resolution 的任务时,我总是感到困惑。关于所报告的问题,我有以下信息:

  • 使用 ASP.NET MVC-5 应用程序
  • 尝试通过以下代码访问字体文件,即MyriadPro-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);
    }
}

路径方面,我不太了解 Visual Studio 在不同类型的应用程序中的工作方式。

最佳答案

你的资源应该被嵌入:

enter image description here

您可以做一个小测试来获取所有资源并找到好名字。之后您的代码似乎是正确的。

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

 var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("fullpath here");
 if (stream == null) return;

编辑

要在 VS 项目中添加文件作为嵌入式资源:只需将文件添加到项目中,单击它,然后在Properties 下将Build Action 设置为嵌入式资源。就是这样!

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

关于c# - Assembly.GetManifestResourceStream 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185053/

相关文章:

Java学习任务+解决方案(小项目)

c# - 我应该将安全代码与不安全代码混合使用吗?

c# - 带有第一个大写字符+数字的正则表达式

c# - 无法获取 DropDownListFor (MVC5) 的选定值

asp.net - MVC5 (VS2012) 标识 CreateIdentityAsync - 值不能为空

c# - 如何从 Designer.cs 文件访问内部静态字符串?

c# - 无法调试使用 Process.Start() 启动的项目

c# - 从不同的项目读取 Properties.Settings.Default

c# - 使用具有不同 LocalHost 和部署 key 的 FaceBook OAuth mvc5

java - @Resource注解在运行时为空