Sharepoint Online: Copy attachment of list item to a new item using Client object model

末鹿安然 提交于 2019-12-12 02:54:22

问题


I want to read the attachments from one list item (in ItemCreated event) to another, new ListItem. How can I do this with the Client Object Model? All I found is server-side code...

Another question: Are the attachments also deleted when I delete a list item or are they still existing on the server?


回答1:


I got it! The following code worked for me:

private static void NewTryToAttachFiles(ClientContext ctx, Web web, List fromList, ListItem fromItem, List toList, ListItem toItem)
    {
        string src = string.Format("{0}/lists/{1}/Attachments/{2}", web.Url, fromList.Title, fromItem.Id);

        Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(src);
        web.Context.Load(attachmentsFolder);
        FileCollection attachments = attachmentsFolder.Files;

        web.Context.Load(attachments);
        web.Context.ExecuteQuery();

        if(attachments.Count > 0)
        {
            foreach (File attachment in attachments)
            {
                // FileInformation fileInfo = File.OpenBinaryDirect(ctx, attachment.ServerRelativeUrl);

                ctx.Load(toItem);
                var clientResultStream = attachment.OpenBinaryStream();
                ctx.ExecuteQuery();
                var stream = clientResultStream.Value;



                AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation();
                Byte[] buffer = new Byte[attachment.Length];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer);
                attachFileInfo.ContentStream = stream2;
                attachFileInfo.FileName = attachment.Name;

                Attachment a = toItem.AttachmentFiles.Add(attachFileInfo);
                ctx.Load(a);
                web.Context.ExecuteQuery();
                stream2.Close();
            }
        }
        ctx.Load(toItem);
        ctx.ExecuteQuery();
    }

It copies the attachments of one list item (fromItem) to the new item!



来源:https://stackoverflow.com/questions/34883326/sharepoint-online-copy-attachment-of-list-item-to-a-new-item-using-client-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!