How to access resources in a .net class library from web request

1.6k views Asked by At

Setup: I have a .net 4.5 class library that embeds resources (e.g., images) for reuse by other ASP.NET MVC projects. For example, the class library (named BlockTypesLibrary) has the following path:

  • BlockTypesLibrary (project)
    • Static
      • img
        • Block.png

I set the properties of Block.png to be Build Action == "Embedded Resource" and Copy Type to Output Directory == "Do Not Copy".

Now in my MVC project I reference the BlockTypesLibrary.dll and I using Reflector I see the resources listed ok:

  • BlockTypesLibrary
    • BlockTypesLibrary.dll
    • Resources
      • BlockTypesLibrary.Static.img.Block.png

In the template I have tried to access that resource in many different ways but can't. For example:

  <div >
    <img src="~/BlockTypesLibrary.Static.img.Block.png" alt="Block">
  </div>

Any ideas how to make this work? I also need to include .cshtml templates as resources in the class library.

1

There are 1 answers

1
Rick Su On

You'll need a Controller that will load embeded resource image from another assembly.

Library Project

public class ResourceLoader
{
    public static byte[] Load(string file)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // load resource
            typeof(ResourceLoader).Assembly.GetManifestResourceStream(file).CopyTo(ms);

            return ms.ToArray();
        }
    }

    public static string[] Files()
    {
        // return list of embeded resource available
        return typeof(ResourceLoader).Assembly.GetManifestResourceNames();
    }

}

MVC Project

public class ImgController : Controller
{

    [Route("~/img/embed/{*filename}")]
    public ActionResult Embed(string filename)
    {
        byte[] content = ResourceLoader.Load(filename);
        string mime = MimeMapping.GetMimeMapping(filename);

        return File(content, mime);
    }
}

View.cshtml

<div >
    <img src="/img/embed/BlockTypesLibrary.Static.img.Block.png" alt="Block">
</div>