Friday, 9 March 2012

Move SharePoint List Item (SPListItem) To Sub Folder

Below is a sample code to move SPlist item  from Root Location to sub folder. as every list item have unique url they can treated as File(SPFile). With SPFile Object we know how SPFile.Move() works.

In this sample code will try to move SharePoint list item from root folder to subfolder during ItemAdded Event.

* /Move  List Item to folder ( not Document library folder )
* with sahrepoint 2010(not sure if poosible in MOSS 2007 )
* Key point sahrepont create unique URL for every list item also . it will look like 
* http:///sites//Lists//1_.000    where 1 is SPitem ID
SPWeb web= properties.Web;
//Folder123 is Inside root location of List
string DestinationFolderName="Folder123";

// Source item outside folder Folder123 
SPListItem listitem = properties.ListItem;

SPFile listitemFile = web.GetFile(listitem.Url);

//Create New Destination  URL ../Lists/Folder123/1_.000
string NewDestinationUrl=listitemFile.Url.Replace(listitem.ID.ToString()+"_.000",DestinationFolderName+"/"+listitem.ID.ToString()+"_.000"); 

//Move Item Insite Folder123


Anonymous said...

Do you know, if this is possible in ECMAScript too? Of course without the event receiver, but in a javascript function.


Vijay Mahapatra said...

I think this should be possible through ECMA Script if am not wrong with ECMA script you mean Client object model

Anonymous said...


yes I mean the Client Object Model. Do you have any idea how this could work? I tried it with the following code, but that seems to work only with documents:

function Test() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var taskslib = web.get_lists().getByTitle('LIST');

var currentItem = taskslib.getItemById(1);
var File = currentItem.get_file();

function (sender, args) {
if(File != null) {
var taskUrl = web.get_serverRelativeUrl() + taskslib.get_title() + '/' + File.get_name();



function (sender, args) {
alert('Error occured' + args.get_message())


Thanks and best regards,


senglory said...

Thanks, Vijay, for your post; it really saved me a lot of time. But in my case I noticed one flaw. After execution of .MoveTo() method the copied item appears in the folder, but the original item remains in the list. Moreover, if I delete the original manually via UI, it deletes the copy in the folder as well. What can be a reason for that problem?

Antonio Ciolino said...

You can do listitmes with CSOM, it's a subset of my post at Look for code in the Folders section of the post.

Anonymous said...

Did anyone find a way to do this with client object model?
Moving files is fine but I cannot Access listitem's SP.File.

Markus said...

As you are moving SPFiles why not building your new folder url like this way?
string newDestinationUrl = item.ParentList.RootFolder.Url + "/" + destinationFolderName + "/" + file.Name;