Recently I needed to embed some javascript into an assembly for distribution in an asp.net application. 

Here's how to embed the file:

  1. Create a js file such as WebUtils.js
  2. In Visual Studio, select the file in Solution Explorer and change the Build Action property to "Embedded Resource"
  3. Build the project and the WebUtils.js file is now part of the assembly (you don't need to distibute the js file now it's part of the assembly)

Now to get the resource out using code:

First thing is to determine the resource name.  This will depend on your namespace hierarchy.  If you are not sure use a tool like Reflector to find out, or you can use the code below to return a string array of all resource names in the current assembly:

public static string[] GetResourceNames()

{

Assembly a = Assembly.GetExecutingAssembly();

string [] resNames = a.GetManifestResourceNames();

Array.Sort(resNames);

return resNames;

}

So if we have a resource named Bbits.WebUtils.js we can use the following to include it in our page:

System.IO.Stream script = Assembly.GetExecutingAssembly().GetManifestResourceStream("Bbits.WebUtils.js");

System.IO.StreamReader sr = new System.IO.StreamReader(script);

Page.RegisterClientScriptBlock("WebUtils",sr.ReadToEnd());

sr.Close();

Have fun

Ian