Freigeben über


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.

Comments

  • Anonymous
    April 29, 2009
    PingBack from http://asp-net-hosting.simplynetdev.com/copy-listitems-from-one-custom-list-to-another-then-move-them-into-subfolders/

  • Anonymous
    May 01, 2009
    Top News Stories Microsoft Unveils Its First Online Management Service (Computer World) Microsoft Corp

  • Anonymous
    January 06, 2010
    Hi, It's moving file as expected but changing last modification date .... is there any way we can maintain last modification date to same as previous ? I am doing it using SPImport/SPExport but this is also changing modified date if list item has single version otherwise it's working fine. is it a limitation of MOSS 2007 ? Thanks, Mehul