Quick tip: SPListItem.CopyTo custom method

Fri, Oct 28, 2011 One-minute read

One use for my custom Ribbon buttons could be to move files (or Document Sets) from one library to another. I was trying to get the SPListItem.CopyTo method working, but for various reasons, it refused to play ball.

I came across a handy piece of code that is essentially a custom method for doing the same thing. Couldn’t understand a word of the article, but got the gist of what the code was doing. It essentially creates an item in the target location, and then copies all the field info over to the new item. This works fine for Lists, and even copies attachments, but what about for document libraries, which are setup a bit differently?

This code achieves the same. What you’re able to do is at the time you create the file, use a Hashtable full of all the metadata you want to apply to your new item.

private void CopyItem(SPListItem sourceItem, string destinationListName)
        {
            Hashtable metadata = new Hashtable();
            foreach (SPField f in sourceItem.Fields)
            {
                if (!f.ReadOnlyField && f.InternalName != "Attachments")
                {
                    metadata.Add(f.InternalName, sourceItem[f.InternalName]);
                }
            }

            //copy sourceItem to destinationList
            SPList destinationList = sourceItem.Web.Lists[destinationListName];
            SPFile targetItem = sourceItem.Web.Files.Add(destinationList.RootFolder + "/" + sourceItem.Name, sourceItem.File.OpenBinary(), metadata);

        }

Enjoy.