C#: Embedding Resources in your DLLs

When you have resources such as images, css files or JavaScript files which you do not want exposed to users, editable, or possibly lost during deployment, a good option is to just embed those resources into your DLL and pull them out as needed.

An example would be an ASP.net custom server control used to handle Session Keep Alive. Lets say we have a .js file which holds our client side JavaScript that needs to be loaded and run on the user’s browser. Lets also say that this file exists within our project in the following directory path next to the .cs files which use it, ProjectName/Web/Utilities/.

To embed the .js file into our DLL you simply need to select the file in Visual Studio and in the ‘Properties’ window there is a option for ‘Build Action’ set it to ‘Embedded Resource’. This will cause the file to be embedded into the DLL the next time the project is built.

Next you need a way to pull that resource out at run time for inclusion in the response to the client. To do this you first need to add a reference to that resource in your ‘AssemblyInfo.cs’ file with is located in the ‘Properties’ folder in the project. Simply go to the bottom of that file and add a WebResource entry as seen below.

[assembly: System.Web.UI.WebResource("GraphicNetDesign.ServerControls.Web.Utilities.KeepAlive.js", "text/js")]

You will notice that the entire path (namespace) to the file needs to be specified. This will be the path you pass in when attempting to access the resource from your code. So now in your code you just do the following to pull the .js file and register it for client use.



Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s