Click here to Skip to main content
15,446,510 members
Articles / Web Development / ASP.NET
Posted 5 Sep 2006


85 bookmarked

Load WebForms and UserControls from Embedded Resources

Rate me:
Please Sign up or sign in to vote.
4.89/5 (23 votes)
5 Sep 2006CPOL4 min read
Load WebForms and UserControls from embedded resources.


Have you ever wanted to break up that monolithic web project into multiple projects, or reuse those user controls and web forms in multiple web projects?

Currently, reusing web forms and user controls in multiple ASP.NET projects requires copying the associated aspx and ascx pages. You can put web controls in separate assemblies, but you lose the design-time drag and drop that makes user controls and web forms so easy to create in the first place. If you've ever tried to put a user control or web form in a separate assembly, you probably ended up with a blank page or runtime errors. The reason is because LoadControl() actually reads the ascx or aspx file to populate the Controls collection and then binds them to your class variables. If the ascx file is not found, no controls are added unless you have done so in your code (as is done with WebControls).

What I wanted was the ability to dynamically call LoadControl() from another assembly to reuse user controls in multiple web projects without copying a bunch of ascx files around. Too much to ask?

Would it be possible to embed those ascx and aspx files as assembly resources and then load them? LoadControl() expects a virtual path, and there did not appear to be any way to load a control from a resource stream. Then I found this:

The Solution

The Virtual Path Provider in ASP.NET 2.0 can be used to load ascx files from a location of your choosing. For my purposes I've decided to store the ascx files in the assembly itself. No more outdated ascx pages that don't work with the updated assembly. Only one file to deploy, the assembly itself, and if you add the assembly as a reference, VS will copy it automatically! To do embed the ascx/aspx file into the assembly, you must change the Build Action of the file on the property page to Embedded Resource, the virtual path provider we create will do the rest.

When a Virtual Path needs to be resolved, ASP.NET will ask the most recently registered Virtual Path Provider if the file exists, and if it does, it will call GetFile to obtain the VirtualFile instance.

Before we can load a resource, we need to know what assembly the resource is located in and the name of the resource to load. I've chosen to encode this information into the virtual path. My final URL looks like this:


It's a bit lengthy, but it includes all the information I need. I don't want to intercept all URLs, so we need to be able to identify which URLs to process and which ones to let the default virtual path provider handle. To do this, I've chosen to process only URLs located in App_Resources. This folder doesn't exist, and that's the point as all paths at this location will be intercepted. The second part contains the assembly name, and the final part is the resource name, which includes the namespace.

I've implemented the Virtual Provider as follows:

public class AssemblyResourceProvider : System.Web.Hosting.VirtualPathProvider 
    public AssemblyResourceProvider() {}
    private bool IsAppResourcePath(string virtualPath)
        String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/App_Resource/", 
    public override bool FileExists(string virtualPath)
        return (IsAppResourcePath(virtualPath) || 
    public override VirtualFile GetFile(string virtualPath)
        if (IsAppResourcePath(virtualPath))
            return new AssemblyResourceVirtualFile(virtualPath); 
            return base.GetFile(virtualPath);
    public override System.Web.Caching.CacheDependency 
           GetCacheDependency( string virtualPath, 
           System.Collections.IEnumerable virtualPathDependencies, 
           DateTime utcStart)
    if (IsAppResourcePath(virtualPath))
        return null;
        return base.GetCacheDependency(virtualPath, 
               virtualPathDependencies, utcStart);

IsAppResource is a private helper method used to determine if we should process the request or let the default provider process the request. Virtual Path Providers are chained together, so it is important that you call the base class. It was also necessary to override GetCacheDependency to return null, otherwise ASP.NET will try to monitor the file for changes and raise a FileNotFound exception. Notice that GetFile returns an instance of AssemblyResourceVirtualFile, this class provides an Open() method to get the resource stream, and is implemented as follows:

class AssemblyResourceVirtualFile : VirtualFile
    string path;
    public AssemblyResourceVirtualFile(string virtualPath) : base(virtualPath)
        path = VirtualPathUtility.ToAppRelative(virtualPath); 
    public override System.IO.Stream Open()
        string[] parts = path.Split('/');
        string assemblyName = parts[2]; 
        string resourceName = parts[3];
        assemblyName = Path.Combine(HttpRuntime.BinDirectory, 
        System.Reflection.Assembly assembly = 
        if (assembly != null)
            return assembly.GetManifestResourceStream(resourceName);
        return null;

All we need to do here is parse virtualPath to get the assembly name and resource name. I'm assuming the assembly is located in the bin directory as it is the typical place for them, and GetManifestResourceStream does all the hard work.

All we need to do now is tell ASP.NET to use our virtual path provider. This can be done in one of two places: Global.asax Application_Start(), or a static method with the following signature in any class file in the App_Code directory:

public static void AppInitialize() { ... }

The important thing is that it must be registered before any virtual paths trapped by our provider can be resolved. I chose to put this in the Application_Start, which looks like the following.

protected void Application_Start(object sender, EventArgs e)
       new AssemblyResourceProvider());

Now, we can load our custom controls into a PlaceHolder using the usual LoadControl, as follows:

protected void Page_Load(object sender, EventArgs e)
    Control ctrl = LoadControl("/App_Resource/WebApplicationControls.dll/"+

The URLs are a bit lengthy because they include information about the assembly and class name, but you can intercept any URL you want. I chose to prefix it with App_Resources to more easily identify what URLs to intercept. An alternate approach might be to define a Virtual Path Provider that uses reflection to search all assemblies in the bin directory for resources ending in ascx/aspx and intercept only those URLs with or without a namespace.

Using the Code

The demo project uses the Web application project update for VS 2005 which can be found here: MSDN.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

Questionmono Pin
Member 1421061917-Apr-19 20:44
MemberMember 1421061917-Apr-19 20:44 
Question.resx files Pin
Member 1021075627-Sep-16 1:47
MemberMember 1021075627-Sep-16 1:47 
QuestionDLL file is left open Pin
drlloyd227-Mar-15 6:05
Memberdrlloyd227-Mar-15 6:05 
Questionnice article but not working with IIS 7.5 Pin
manoharmind26-Oct-14 22:11
Membermanoharmind26-Oct-14 22:11 
QuestionWorking right up to LoadControl Pin
drlloyd222-Oct-14 4:03
Memberdrlloyd222-Oct-14 4:03 
AnswerRe: Working right up to LoadControl Pin
drlloyd228-Oct-14 3:44
Memberdrlloyd228-Oct-14 3:44 
QuestionCan we use this approach in MVC and pass a model to the control? Pin
priyada4-Mar-14 23:51
Memberpriyada4-Mar-14 23:51 
QuestionHow to access methods and properties in customer user controls from web pages Pin
wilpho12-Nov-12 21:40
Memberwilpho12-Nov-12 21:40 
GeneralMy vote of 5 Pin
hallz18-Feb-12 22:36
Memberhallz18-Feb-12 22:36 
NewsFantastic Pin
PAKDev15-Sep-11 22:47
MemberPAKDev15-Sep-11 22:47 
GeneralNice code ! Pin
obst90028-Jul-10 11:01
Memberobst90028-Jul-10 11:01 
GeneralWonderful, but not working on VS 2008 (.NET 3.5) Pin
asewefy28-Dec-09 7:59
Memberasewefy28-Dec-09 7:59 
GeneralRe: Wonderful, but not working on VS 2008 (.NET 3.5) Pin
ApocalipseIsNear4-Mar-13 21:07
MemberApocalipseIsNear4-Mar-13 21:07 
GeneralLoading aspx files Pin
ken9989-Dec-09 5:31
Memberken9989-Dec-09 5:31 
Questionjavascript Pin
Waxime645-May-09 4:22
MemberWaxime645-May-09 4:22 
QuestionRe: javascript Pin
mina_saif30-May-11 4:27
Membermina_saif30-May-11 4:27 
GeneralhttpHandler help Pin
hitz1721-Mar-09 12:56
Memberhitz1721-Mar-09 12:56 
GeneralRe: httpHandler help Pin
hitz1721-Mar-09 14:32
Memberhitz1721-Mar-09 14:32 
Questionusing VirtualPathProvider Pin
amruta_muley25-Feb-09 3:09
Memberamruta_muley25-Feb-09 3:09 
AnswerRe: using VirtualPathProvider Pin
Kurt Harriger25-Feb-09 16:33
MemberKurt Harriger25-Feb-09 16:33 
GeneralDoesn't work when running 3.5 medium trust Pin
oc00l30-Dec-08 2:30
Memberoc00l30-Dec-08 2:30 
GeneralDeployment on Sharepoint Pin
vicgrad21-Oct-08 0:41
Membervicgrad21-Oct-08 0:41 
GeneralRe: Deployment on Sharepoint Pin
Kurt Harriger27-Oct-08 18:13
MemberKurt Harriger27-Oct-08 18:13 
QuestionDoes anyone have this working in production? Pin
imxuf12-Aug-08 9:58
Memberimxuf12-Aug-08 9:58 
AnswerRe: Does anyone have this working in production? Pin
Kurt Harriger12-Aug-08 13:02
MemberKurt Harriger12-Aug-08 13:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.