Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.GetManifestResourceStream always returns null

It is always confusing for me whenever I get to the tasks of Path-Resolution. I have the following information regarding the issue reported:

  • Using ASP.NET MVC-5 Application
  • Trying to access a font file i.e. MyriadPro-SemiBold.ttf via below code
//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);
    }
}

I don't know much about the way Visual Studio works in different types of Applications in the aspect of paths.

like image 353
Asif Mehmood Avatar asked Oct 11 '25 17:10

Asif Mehmood


1 Answers

Your resource should be embedded:

enter image description here

You can make a little test to get all your resources and find the good name. After that your code seems correct.

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

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

EDIT

To add a file in VS project as embedded resource: just add the file to your project, click on it, and then under Properties set Build Action to Embedded Resource. And that's it!

More information about embedded resource: https://support.microsoft.com/en-us/kb/319292#bookmark-4

like image 153
halfer Avatar answered Oct 14 '25 11:10

halfer