Assembly.GetManifestResourceStream总是返回null。

4

每当我需要进行路径解析时,都感到困惑。以下是关于报告问题的信息:

  • 使用 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在路径方面的工作方式并不了解。


1
System.Reflection.Assembly.ReflectionOnlyLoadFrom(path)?可能是https://dev59.com/9Wgv5IYBdhLWcg3wQ-qd的重复问题。 - Seth Kitchen
您提供的代码行给了我一个异常**{"无法加载文件或程序集 'file:///C:\Program Files.....\myApplicationName.fonts.MyriadPro-Semibold.ttf' 或其某个依赖项。系统找不到指定的文件。":"file:///C:\Program Files....\myApplicationName.fonts.MyriadPro-Semibold.ttf"}**。 - Asif Mehmood
1
你的路径看起来有误。去掉 file:/// 中的双斜杠,并确保文件名位于文件资源管理器中的那个目录下。 - Seth Kitchen
是的,这也是解决方案。非常感谢@SethKitchen。下面被接受的答案对我有用。 - Asif Mehmood
1个回答

14

您的资源应该被嵌入:

在此输入图片描述

您可以进行一些小测试来获取所有资源并找到正确的名称。之后,您的代码似乎是正确的。

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

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

编辑

要将文件添加为 VS 项目的嵌入式资源:只需将文件添加到您的项目中,点击它,然后在属性下设置生成操作嵌入的资源。就是这样!

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


在调试时,allRessources得到{string[0]}。这是否意味着我的资源未嵌入?(我不知道嵌入式资源,你能分享一些东西吗?) - Asif Mehmood
2
是的,我认为你的资源没有被嵌入。如果你正在使用Visual Studio,只需将文件添加到你的项目中,点击它,然后在“属性”下设置“生成操作”为“嵌入式资源”。就这样! - Quentin Roger
现在在调试时,资源正在 allRessources 中显示。感谢这个。 - Asif Mehmood
我很高兴这对你有所帮助。 - Quentin Roger
1
@QuentinRoger 经过漫长的搜索,我终于来到这里找到了完美的解决方案。对你致以无尽的感谢! - mankers
谢谢你,我需要使用嵌入资源而不是资源,因为我已经将我的 .NET Framework 从4.8更改为.NET 7。 - Rachid Benbrik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接