I came across a problem whereby I needed to add a Web Part to the Web Part Gallery. The Web Part had been deployed successfully but as of yet it did not appear in the Web Part Gallery SPList. This needed to be done programmatically by using the SharePoint object model.
How do we programmatically add a Web Part (that has been deployed) to the Web Part Gallery. Using the SharePoint UI this is done via the NewDwp.aspx page.
The problem is that the list you see on the NewDwp.aspx page is not an SPList! Which makes life a bit tough! The other problem is that the .dwp files displayed in there do not exist until you select them and then click “Populate” by which time they are already in the Web Part Gallery.
I believe the NewDwp.aspx page builds the list of Web Parts, available to be added to the Gallery, from the web.config safe control enteries. Once you click “Populate” the page dynamically builds the .dwp file and adds it to the Gallery.
To add the Web Part to the Gallery programmatically you have to do the same i.e.
- Create the .dwp xml file dynamically
- Add it to the Web Part Gallery SPList
Below is the code to achieve this:
private static void AddWebPartToGallery()
using (SPSite site = new SPSite("http://yoursite.com"))
using (SPWeb web = site.OpenWeb())
FileInfo fInfo = new FileInfo("myFile.dwp");
FileStream fStream = fInfo.Open(FileMode.Open, FileAccess.Read);
web.AllowUnsafeUpdates = true;
site.AllowUnsafeUpdates = true;
SPList list = web.Lists["Web Part Gallery"];
SPFolder root = list.RootFolder;
SPFile spFile = root.Files.Add("ContentEditor.dwp", s);
The CreateDwpFile() method dynamically creates the .dwp file. Then open the Web Part Gallery List and the newly created .dwp file and add it to the root folder of the list.