Search code examples
c#sharepointsharepoint-2013splistitemsplist

How can I programatically move an SPListItem from a source list to a destination list (into a specific folder of the list)?


I am pretty new in SharePoint (I am working with SharePoint 2013) and I have the following problem:

I have a source list(an SPList) on a source website and I have to move its items to a destination list (another SPList) on a destination website.

So basically I have to move some SPListItem from a list to another on two different website.

A further complication is that the destination list contains folder based on a date field on the item in migration (for example: if the date is: 2019/05/28 it will be created the following folders into the destination list like this 2019 --> 05 --> 28 where this SPListItem have to be put).

I know that I can do something like this:

private static void copyAttachments(SPListItem sourceItem, SPList sourceAttachList, SPList destAttachList, string destUrl)
{
    // Create the destination item for the attachments:
    SPListItem destAttachItem = null;

    string recNumber = sourceItem[Arxeia6Fields.NumeroProtocollo].ToString();
    DateTime recDate = (DateTime)sourceItem[Arxeia6Fields.DataProtocollo];

    /*
     * Add an item in a specific server-relative URL of the folder where the list item should be created.
     * The new list item represents a file.
     */
    destAttachItem = destAttachList.AddItem(destUrl, SPFileSystemObjectType.File);
    string title = recNumber + "/" + recDate.Year.ToString();
    destAttachItem["Title"] = title;
    destAttachItem["Numero protocollo"] = title;

}

With this code I am creating adding a new item to the destination list (named destAttachList specifyng the destUrl representing the exact folder in this list where put the item (I have this information from a previous process step). Then I simply set the values of the 2 fields of this item in the destination list using the values of the item of the source list that I am migrating.

My doubts are:

  1. Can I move the item from a source list to a destination list (in a specific folder specified by a destination URL)?

  2. If this item in migration contains attachments, these attachments can be automatically migrated by this single move step? (if it is possible)


Solution

  • You don't have to do all those things manually as SharePoint already has this method implemented out of the box. You don't even need an additional method, you shoud be able to achieve all those things by calling the MoveTo method.

    sourceItem.File.MoveTo(SPUrlUtility.CombineUrl(destinationList.ParentWeb.Url,destinationList.RootFolder.Url));

    Where, of course, the sourceItem si the SPListItem that you want to move and destinationList is the SPList that should serve as destination for the SPListItem.