Search code examples
sharepoint-2010sharepointdocumentlibrarysharepoint-clientobject

Creating a SharePoint 2010 page via the client object model


I am attempting to create pages in a Sharepoint 2010 pages library via the client object model but I cannot find any examples on how to do it. I have tried two approaches:

The first is to treat the Pages library as a list and try to add a list item.

static void createPage(Web w, ClientContext ctx)
{
    List pages = w.Lists.GetByTitle("Pages");
    //ListItem page = pages.GetItemById(0);
    ListItemCreationInformation lici = new ListItemCreationInformation();
    ListItem li = pages.AddItem(lici);
    li["Title"] = "hello";
    li.Update();
    ctx.ExecuteQuery();            
}

As expected, this failed with the error message:

To add an item to a document library, use SPFileCollection.Add()

The next approach I tried was to add it as a file. The problem is that the FileCreationInformation object is expecting a byte array and I am not sure what to pass to it.

static void createPage(Web w, ClientContext ctx)
{
    List pages = w.Lists.GetByTitle("Pages");
    FileCreationInformation file = new FileCreationInformation();
    file.Url = "testpage.aspx";
    file.Content = new byte[0];
    file.Overwrite = true;
    ctx.Load(pages.RootFolder.Files.Add(file));
    ctx.ExecuteQuery();    
}

The piece of code above will add an item in the Pages library but opening the file brings up a blank page which I cannot edit. From reading various topics, I suspect that it may only be possible to add pages via server side code. Any thoughts?

Thanks


Solution

  • The problem is that the FileCreationInformation object is expecting a byte array and I am not sure what to pass to it.

    You could you whatever method you want to get the page contents into a string (read it from a file, create it using a StringBuilder, etc) and then convert the string to a byte array using

    System.Text.Encoding.ASCII.GetBytes()