使用客户端对象模型在文档库中创建空白文档

时间:2015-03-13 03:24:17

标签: c# sharepoint office365

我正在创建一个函数,您可以在其中提供内容类型名称并定位列表或文档库并创建默认项目。我正在使用Office 2013的客户端对象模型

public void MyFunction()
{
   //clientContext must be authenticated already on your sharepoint site

   var listName = "Default Document Set";
   var docSetContentTypeName = "Document";
   var newDocSetName = string.Format("Item {0}", Guid.NewGuid());

   Web web = clientContext.Web;
   List list = clientContext.Web.Lists.GetByTitle(listName);

   clientContext.Load(clientContext.Site);

   ContentTypeCollection listContentTypes = list.ContentTypes;
   clientContext.Load(listContentTypes, types => types.Include
                              (type => type.Id, type => type.Name,
                              type => type.Parent));

   var result = clientContext.LoadQuery(listContentTypes.Where
    (c => c.Name == docSetContentTypeName));

   clientContext.ExecuteQuery();

   ContentType targetDocumentSetContentType = result.FirstOrDefault();

   ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
   newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
   newItemInfo.LeafName = newDocSetName;
   ListItem newListItem = list.AddItem(newItemInfo);

   newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
   newListItem["Title"] = newDocSetName;
   newListItem.Update();

   clientContext.Load(list);
   clientContext.ExecuteQuery();
}

该功能在项目和文档集等ContentTypes上正常工作,但是当我使用Document时,它会创建一个内容类型为“Document”的项目,但它有一个文件夹图标,就像一个文件夹。 Document Type

我需要添加什么吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

FileSystemObjectType.Folder用于创建Folder对象,因此可以指定创建File对象。同时List.AddItem Method可以用于创建文件对象

您可以考虑以下示例演示如何在文档库中创建(上载)文件:

public static void UploadFile(List list,string filePath,IDictionary<string,object> itemProperties)
{
        var ctx = list.Context;
        var fileInfo = new FileCreationInformation();
        fileInfo.Url = Path.GetFileName(filePath);
        fileInfo.Overwrite = true;
        fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
        var file = list.RootFolder.Files.Add(fileInfo);
        var listItem = file.ListItemAllFields;
        foreach (var p in itemProperties)
        {
            listItem[p.Key] = p.Value;
        }    
        listItem.Update();
        ctx.ExecuteQuery();
}

使用Open XML SDK 2.0 for Microsoft Office您可以创建一个空文档并将其上传到文档库:

public static void CreateAndUploadFile(List list, string filePath, IDictionary<string, object> itemProperties)
{
    using (var document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
    {
        var mainPart = document.AddMainDocumentPart();
        mainPart.Document = new Document(new Body());
    }
    UploadFile(list, filePath, itemProperties);
}

用法:

var list = web.Lists.GetByTitle(listTitle);
var itemProperties = new Dictionary<string,object>();
itemProperties["Title"] = "SharePoint User Guide";
CreateAndUploadFile(list, "./SharePoint User Guide.docx", itemProperties);