Skip to content

Overwrite files in SharePoint Template Galleries with feature

June 9, 2011

When creating a SharePoint feature, the Elements manifest can be used to upload files to the different template galleries such as the Site Template, Web Part, List Template and Master Page Gallery.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
	<Module Name="ABC_SiteTemplates" List="111" Url="_catalogs/wt" >
		<File Url="ABC_template1.stp" Type="GhostableInLibrary">
			<Property Name="LanguageDisplay" Value="English" />
			<Property Name="Version" Value="1" />
		</File>
	</Module>
</Elements>

I would expect that when a new version of the feature is installed then the uploaded files get replaced with the new template or web part files but no. Once a file is in the gallery it is not overwritten with new versions.

One solution to resolve this issue and have the files overwritten is to delete the files when the feature is deactivated so on next activation the files will not be there and the new versions will be uploaded.

We use the following code in a SPFeatureReceiver to delete the existing files from a Site Template Gallery. Just replace “wt” with “wp” to do the same for webpart galleries, with “lt” for list template galleries and “masterpage” for the master page gallery.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
	SPSite site = properties.Feature.Parent as SPSite;
	SPWeb web = site.RootWeb;

	SPFileCollection templates = web.Folders["_catalogs"].SubFolders["wt"].Files;

	int templateCount = templates.Count;
	for (int i = templateCount -1; i >= 0; i--)
	{
		if (templates[i].Name.StartsWith("ABC"))
			templates[i].Delete();
	} 				
}

Note that in this case SPSite and SPWeb don’t need to be disposed so don’t put them in using blocks.

Advertisements
Leave a Comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: