The ClassResourcePath for custom webparts in MOSS 2007

At Macaw we've been using standard project templates for most of our development projects for years. In the project template for custom webparts for SharePoint 2003 we've had a basewebpart. All custom webparts for SharePoint 2003 inherit from the basewebpart. On of the things the basewebpart takes care of is determining the ClassResourcePath.

Custom web parts can be deployed to the wwwroot/bin directory or to the global assembly cache (GAC). The deployment location also affects the location where resources (for instance usercontrols and images) that are required by the web part are stored. For GAC deployments, the directory is mapped to /_wpresources/[assembly_name]. For bin directory deployments, the directory is mapped to /wpresources/[assembly_name].

In order to determine the resource path at runtime you use the ClassResourcePath of Microsoft.SharePoint.WebPartPages.WebPart.


For SharePoint 2007 Microsoft recommends inheriting custom webparts from System.Web.UI.WebControls.WebParts.WebPart. Unfortunately this class doesn't contain an equivelant of the ClassResourcePath. However if you're building a basewebpart that will be used by a lot of custom web parts you do want to be able to determine the path where the resources are stored at runtime, since you don't beforehand know whether a web part will be deployed in the bin or in the GAC.

In order to be able to do this I've used SPWebPartManager.GetClassResourcePath. You can use this class, that is inherited from Microsoft.SharePoint.WebPartPages and at the same time inherit the web part itself from System.Web.UI.WebControls.WebParts.WebPart in order to comply with Microsoft recommendations.

The code getting the resource path will look like this:

SPWeb currentWeb = SPControl.GetContextWeb(Context);
Type currentType = BaseWebPart.GetType();
string classResourcePath = SPWebPartManager.GetClassResourcePath(currentWeb, currentType);