2

The following function copies the attachments from 1 list item to another, notice the byte[] binFile = file.OpenBinary(); line, won't this keep an open hook on this file? Do I need to take some manual action to dispose this hook?

private static bool copyAttachments(string websiteURL, string src_List, int src_ID, string dest_List, int dest_ID)
        {
            using (SPSite Site = new SPSite(websiteURL))
            {
                using (SPWeb web = Site.OpenWeb())
                {
                    SPList sourceList = web.Lists[src_List];
                    SPListItem sourceItem = sourceList.Items.GetItemById(src_ID);
                    SPList destList = web.Lists[dest_List];
                    SPListItem destItem = destList.Items.GetItemById(dest_ID);

                    SPFolder sourceItemAttachmentsFolder = sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];

                    foreach (SPFile file in sourceItemAttachmentsFolder.Files)
                    {
                        byte[] binFile = file.OpenBinary();
                        destItem.Attachments.AddNow(file.Name, binFile);
                    }
                }
            }  
4

No need to dispose when using OpenBinary. However, the stream that comes back from the OpenBinaryStream method will need to be disposed or you will run into problems very quickly.

I have written a post about that particular scenario.

Code for copying attachments can be found in this post about synchronising two SharePoint lists.

1

The OpenBinary just gives you a copy of the binary contents of the SPFile, copied into the byte[] array. You do not need to dispose it, the GC takes care of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.