Move existing SPListItem to new location

Almost every SharePoint developer knows popular SPFile.MoveTo method. But, in certain cases, you have only SPListItem, and you need to move it to new destination.

One of the possible solutions is to make a fake SPFile from this SPListItem, and move the fake SPFile.

SPListItem itemToMove;
SPList list = itemToMove.ParentList;
SPWeb web = itemToMove.Web;
SPFile fileFake = web.GetFile(itemToMove.Url);

string listRootFolderUrl= list.RootFolder.ServerRelativeUrl.TrimEnd(new Char[] { '/' });
string destinationFolderPath; //url of destination folder
string destinationUrl = listRootFolderUrl + "/" + destinationFolderPath + "/" + itemToMove.ID + "_.000";
fileFake.MoveTo(destinationUrl);

Another solution could be to create new SPListItem in desired location, copy metadata and remove old item. But this method will make problems, if there were existing some lookups pointing to the old deleted item – the lookups will be logically empty.

Marek

Currently working as SharePoint Developer combining both back-end & front-end development scenarios. Also enthusiastic about Office 365 & Azure solutions.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *