http://www.habaneros.com/blog/posts/Programmatically_change_content_on_a_Wiki_Page_in_SharePoint_2010.aspx
Adjusted slightly to work for me
protected void lblAddWP_Click(object sender, EventArgs e)
{
AddWebPartToPage(SPContext.Current.Site.OpenWeb(), lblInfo.Text + "/SitePages/Home.aspx", "ActionSubjectGridy", "Top", 0);
lblAdd.Text = "Added WP ";
}
public void AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
{
InsertWebPartIntoWikiPage("TopWebPart");
InsertWebPartIntoWikiPage("ActionSubjectGridy");
}
public void InsertWebPartIntoWikiPage(string webPartName)
{
string replaceToken = "{{1}}";
using (SPSite site = new SPSite(lblInfo.Text))
{
using (SPWeb web = site.OpenWeb())
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(web.Url + "/SitePages/Home.aspx", PersonalizationScope.Shared))
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager))
{
SPFile wikiFile = web.GetFile("SitePages/Home.aspx");
string str = (string)wikiFile.Item["WikiField"];
SPLimitedWebPartManager limitedWebPartManager = wikiFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
Guid storageKey = Guid.NewGuid();
string str2 = StorageKeyToID(storageKey);
webPart.ID = str2;
limitedWebPartManager.AddWebPart(webPart, "wpz", 0);
string str3 = string.Format(CultureInfo.InvariantCulture, "<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'><div class='ms-rtestate-read {0}' id='div_{0}'></div><div style='display:none' id='vid_{0}'/></div>", new object[] { storageKey.ToString("D") });
if (str == null)
{
str = str3;
}
else
{
if (!str.Contains(replaceToken)) { str = str + str3; } else { str = str.Replace(replaceToken, str3); }
}
wikiFile.Item["WikiField"] = str;
wikiFile.Item.Update();
}
}
}
}
}
public static string StorageKeyToID(Guid storageKey) { if (!(Guid.Empty == storageKey)) { return ("g_" + storageKey.ToString().Replace('-', '_')); } return string.Empty; }
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
{
SPQuery query = new SPQuery();
query.Query = String.Format(CultureInfo.CurrentCulture,
"<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>",
webPartName);
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
SPListItemCollection webParts = webPartGallery.GetItems(query);
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMessage;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
return webPart;
}