Programmatically adding Web Parts to a page

I have recently had to come up with a way to programmatically add a Web Part to a large number of existing publishing pages. It took me a little while to find the exact way to do it, so I thought I would post the source code here.

Attached is the C# code that will iterate over a bunch of pages in a bunch of sites, and then add a doclib Web Part on all those pages, in a specific Web Part Zone. The meat of the code is this:

SPSite mySiteCollection = new SPSite("https://sharepoint");SPWeb w = mySiteCollection.AllWebs["/whatever"];SPFile f = w.GetFile("Pages/Page.aspx");SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);SPList l = w.Lists["Documents"];ListViewWebPart wp = new ListViewWebPart();wp.ListName = l.ID.ToString("B").ToUpper();wp.ViewGuid = l.DefaultView.ID.ToString("B").ToUpper();wpm.AddWebPart(wp, "Zone 1", 1);f.Publish("Added Web Part");f.Approve("Web Part addition approved");

This bit of code uses an SPLimitedWebPartManager to add the ListViewWebPart to the "Zone 1" Web Part Zone. The page is then published and approved.

 

Program.cs