Search code examples
.netembedded-resource

Javascript as embedded resource in a .NET Class library?


I'm running an MVC project which references a class library. The class library contains a javascript file which build action is set to "Embedded resource".

What actually happens to the file? I can't seem to get it using the ResourceManager because I have no idea of the namespace it puts the resource in.

My class library file structure:

  • /Project
  • /Project/Web
  • /Project/Web/Js
  • /Project/Web/Js/Test.js << embedded resource

Code:

var t = this.GetType().Assembly;
var r = new System.Resources.ResourceManager("Namespace", t); //What is the namespace here?
var js = r.GetObject("Test.js");

Solution

  • Sorry, I dont have access to a compiler right now so the following might contain slight errors.

    var asm = typeof(MyClass).Assembly;
    var stream = asm. GetManifestResourceStream("<rootnamespace>.Project.Web.Js.Test.js");
    var reader = new StreamReader(stream);
    String source = reader.ReadToEnd();
    

    Notes:

    • use typeof(x) instead of GetType(). The latter will give incorrect result if you inherit from the type.
    • rootnamespace can be found/set in the project settings. (I assumed that "Project" is a folder inside the project in my example)
    • asp.net has a pre-build solution for using resources this way. Try looking into Page.ClientScript for this. (I'm not sure if this also works for MVC, but would bet that it would)