Copy listitems from one custom list to another, then move them into subfolders.

One problem I stumbled over the other day, was how to copy item from one custom SPlist to another. The two lists are identical and I thought moving the items should be quite easy through use of the object model. It turned out be not so straight forward.

Normally, SPListItem.CopyFrom() and SPListItem.CopyTo() should do the trick:

SPListItem listItem = web.GetListItem(listItemUrl);
listItem.CopyTo(destinationUrl); // Copies the item to the specified destinations

or

listItem.CopyFrom(sourceUrl); // Overwrites the current item with the specified version of the item.

Sadly, this does not work with custom lists or custom properties. A small search on live.com showed that I was not the only one struggling with this. Several solutions are available like:
https://www.communardo.de/techblog/2008/01/08/sharepoint-listenelement-splistitem-in-eine-andere-liste-kopieren/ (you can read the code… )
https://www.informationworker.co.za/blogs/mirror/Lists/Posts/Post.aspx?ID=312

https://www.k2distillery.com/2007/10/copy-version-history-with_5.html

So, there is not really need for another posting of this code. Except for the fact that I wanted to move the copied item into subfolders. Trying to do so resulted in the error:
”Source item cannot be found. Verify that the item exists and that you have permission to read it.”
It doesn’t tell you much now does it?

But, if I combined the logic from the posts above with a SPFile.MoveTo(…) it was finally working OK.

SPListItem item = Web.Lists["Announcement"].GetItemById(5);
SPFile file = Web.GetFile(item.Url);
file.MoveTo("New location...with the ID_.000");

https://blogs.inetium.com/blogs/khofer/archive/2008/03/16/fix-can-t-move-copy-an-splistitem.aspx

Summarized:

1. Copy the item by iterating through all fields, and optionally for all versions of the item

2. Copy the attachments.

3. Delete the original item, if applicable.

4. Move the new item into appropriate subfolder.

 

Hope this can save you time if you need to do the same sort of thing.