sharepointsharepoint-appssharepoint-clientobject

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


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?


Solution

  • 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!