Embedding javascript in an assembly

I've always been able to create a standalone DLL control that can be reused in other web applications.  I've never really found out how to embed other resources, or more to the point JavaScript files.

Until now

Here's how to embed the file:

  1. Create a js file such as carousel.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 carousel.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:

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

System.IO.Stream script = Assembly.GetExecutingAssembly().GetManifestResourceStream("Control.carousel.js");
System.IO.StreamReader sr = new System.IO.StreamReader(script);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "carousel", sr.ReadToEnd().ToString(), true);
sr.Close();
The above code injects the embedded file in to the page, how easy could it be?

 

blog comments powered by Disqus

About the author

You have probably figured out by now that my name is Bryan Avery (if not, please refer to your browser's address field).  Technology is more than a career to me - it is both a hobby and a passion.  I'm an ASP.NET/C# Developer at heart...

Month List