Add attachments to sharepoint list item programmatically

17/01/2018 17:17
 Copy splistitem attachments to other list item.
If any changes were done on destItem, there must be saved before adding attachments
 
 
public static SPFieldUrlValue UpdateAttachments(SPListItem sourceItem, SPListItem destItem)
        {
            SPFieldUrlValue attachmentUrlValue = null;
            try
            {
                var sourceAttachments = sourceItem.Attachments;
                if (sourceAttachments != null && sourceAttachments.Count > 0)
                {
                    var attachmentFolder = sourceItem.ParentList.RootFolder.SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
                    foreach (SPFile file in attachmentFolder.Files)
                    {
                        var fileBytes = file.OpenBinary();
                        destItem.Attachments.AddNow(file.Name, fileBytes);
                        destItem.SystemUpdate();
 
                        var fileDestUrl = SPUrlUtility.CombineUrl(destItem.Attachments.UrlPrefix, file.Name);
                        attachmentUrlValue = new SPFieldUrlValue() { Url = fileDestUrl };
                    }
                }
            }
            catch (Exception e)
            {
                LogService.LogError(e);
            }
 
            return attachmentUrlValue;
        }