SharePoint 2010 - Client Object Model - Add attachment to ListItem

前端 未结 6 992
傲寒
傲寒 2020-12-30 05:43

I have a SharePoint List to which I\'m adding new ListItems using the Client Object Model. Adding ListItems is not a problem and works great.

Now I want to add att

6条回答
  •  攒了一身酷
    2020-12-30 06:11

    With Sharepoint 2010 there was no way to upload a first attachment to a list item using the COM. The recommendation was to use the Lists web service inmstead.

    With Sharepoint 2013 it works.

    AttachmentCreationInformation newAtt = new AttachmentCreationInformation();
    newAtt.FileName = "myAttachment.txt";
    // create a file stream
    string fileContent = "This file is was ubloaded by client object meodel ";
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    byte[] buffer = enc.GetBytes(fileContent);
    newAtt.ContentStream = new MemoryStream(buffer);
    
    // att new item or get existing one
    ListItem itm = list.GetItemById(itemId);
    ctx.Load(itm);   
    // do not execute query, otherwise a "version conflict" exception is rised, but the file         is uploaded
    // add file to attachment collection
    newAtt.ContentStream = new MemoryStream(buffer);
    itm.AttachmentFiles.Add(newAtt); 
    AttachmentCollection attachments = itm.AttachmentFiles;
    ctx.Load(attachments);
    ctx.ExecuteQuery(); 
    // see all attachments for list item
    // this snippet works if the list item has no attachments
    

    This method is used in http://www.mailtosharepoint.net/

提交回复
热议问题