C# – How to programmatically create editable wiki pages within the Pages library of an Enterprise Wiki site

csharepointsharepoint-2010sharepoint-api

I'm new to SharePoint. I'm trying to programmatically create a wiki page within the Pages library of an Enterprise Wiki site in SharePoint 2010. Here is my code:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
        SPWeb rootWeb = site.RootWeb;
        rootWeb.AllowUnsafeUpdates = true;
        SPList wiki = rootWeb.Lists["Pages"];
        SPFolder rootFolder = wiki.RootFolder;
        SPFile wikiPage = rootFolder.Files.Add(String.Format("{0}/{1}", rootFolder.ServerRelativeUrl, "MyWikiPage.aspx"), SPTemplateFileType.WikiPage);
        SPListItem wikiItem = wikiPage.Item;
        wikiItem["PublishingPageContent"] = "my demo content";
        wikiItem.UpdateOverwriteVersion();
        rootWeb.AllowUnsafeUpdates = false;
}

The page gets created but the problem is that the created page is not editable and the demo content is not inserted. When opened in edit mode, no content space is available and edit options are greyed out.

I have also tried setting the default content like this:

    wikiItem[SPBuiltInFieldId.WikiField] = "my demo content";

But that gives an invalid field error.

I have also tried creating the page with this line of code instead:

    SPFile wikiPage = SPUtility.CreateNewWikiPage(wiki, String.Format("{0}/{1}", rootFolder.ServerRelativeUrl, "MyWikiPage.aspx"));

But the result is exactly the same.

I have confirmed that "SharePoint Server Publishing" feature is turned on for the site and "SharePoint Server Publishing Infrastructure" feature is turned on for the site collection.

Please help.

Best Answer

With help from my other thread on sharepoint.stackexchange.com, I came up with this solution:

Instead of targeting the Pages library with regular wiki manipulation routines, we need to create a new Publishing Page and update Content type properties accordingly.

For the benefit of others, here's the code that worked for me:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    SPWeb rootWeb = site.RootWeb;
    rootWeb.AllowUnsafeUpdates = true;
    SPList wiki = rootWeb.Lists["Pages"];
    String url = wiki.RootFolder.ServerRelativeUrl.ToString();
    PublishingSite pubSite = new PublishingSite(rootWeb.Site);
    string pageLayoutName = "EnterpriseWiki.aspx"; //Page Layout Name
    string layoutURL = rootWeb.Url + "/_catalogs/masterpage/" + pageLayoutName;
    PageLayout layout = pubSite.PageLayouts[layoutURL];
    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(rootWeb);
    PublishingPage newWikiPage;
    string myWikiPage = "MyWikiPage.aspx"; //Page name
    newWikiPage = publishingWeb.GetPublishingPages().Add(myWikiPage, layout);
    newWikiPage.Title = "My Wiki Page";
    newWikiPage.Update();
    rootWeb.AllowUnsafeUpdates = false;
}
Related Topic