通过客户端对象模型创建SharePoint 2010页面

时间:2011-06-01 10:52:19

标签: sharepoint-2010 sharepointdocumentlibrary sharepoint-clientobject client-object-model

我正在尝试通过客户端对象模型在Sharepoint 2010页面库中创建页面,但我找不到任何有关如何执行此操作的示例。我尝试了两种方法:

第一种方法是将Pages库视为列表,并尝试添加列表项。

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();            
}

正如所料,这失败并显示错误消息:

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

我尝试的下一个方法是将其添加为文件。问题是FileCreationInformation对象期望一个字节数组,我不知道该传递给它。

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();    
}

上面的代码将在Pages库中添加一个项目,但打开文件会显示一个我无法编辑的空白页面。从阅读各种主题,我怀疑只能通过服务器端代码添加页面。有什么想法吗?

由于

2 个答案:

答案 0 :(得分:2)

  

问题在于   FileCreationInformation对象是   期待一个字节数组,我不是   确定要传递给它的是什么。

您可以使用任何方法将页面内容转换为字符串(从文件中读取,使用StringBuilder创建等),然后使用

将字符串转换为字节数组
  

System.Text.Encoding.ASCII.GetBytes()

答案 1 :(得分:0)

首先,SharePoint 2010 中的客户端对象模型(CSOM)不支持 Publishing API 。但您可以考虑使用以下方法演示如何使用SharePoint 2010 CSOM创建发布页面。

如何使用SharePoint 2010 CSOM创建发布页面

public static void CreatePublishingPage(ClientContext ctx, string listTitle, string pageName, string pageContent)
{
        const string publishingPageTemplate = "<%@ Page Inherits=\"Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%@ Reference VirtualPath=\"~TemplatePageUrl\" %> <%@ Reference VirtualPath=\"~masterurl/custom.master\" %>";
        var pagesList = ctx.Web.Lists.GetByTitle(listTitle);
        var fileInfo = new FileCreationInformation
        {
            Url = pageName,
            Content = Encoding.UTF8.GetBytes(publishingPageTemplate),
            Overwrite = true
        };
        var pageFile = pagesList.RootFolder.Files.Add(fileInfo);
        var pageItem = pageFile.ListItemAllFields;

        if (!ctx.Site.IsPropertyAvailable("ServerRelativeUrl"))
        {
            ctx.Load(ctx.Site);
            ctx.ExecuteQuery();
        }
        pageItem["PublishingPageLayout"] =  string.Format("{0}_catalogs/masterpage/ArticleLeft.aspx, ArticleLeft",ctx.Site.ServerRelativeUrl);
        pageItem["PublishingPageContent"] = pageContent;
        pageItem.Update();
        ctx.ExecuteQuery();
}

<强>用法

using (var ctx = new ClientContext(url))
{ 
     ctx.Credentials = new NetworkCredential("username", "password", "domain");
     CreatePublishingPage(ctx, "Pages", "Greetings.aspx", "Welcome to SharePoint!"); 
}