Saturday, May 11, 2013

Copy or Move files from one folder to another folder using SharePoint 2010 object model

In this article we will discuss about how to copy files from one folder to another folder using SharePoint 2010 object model.

Also you can check out my previous posts on: CAML designer for SharePoint 2013, custom timer job sharepoint 2010 and SharePoint 2010 Centered Fixed Width Design.

Copy files in SharePoint:

SPWeb mySite = SPContext.Current.Web;

SPFolder myFolder = mySite.GetFolder("MySourceFolder");
SPFileCollection myFiles = myFolder.Files;

foreach (SPFile file in myFiles)
   {

     file.CopyTo("MyDestinationFolder/" + file.Name, true);

   }

Here the CopyTo method uses two parameters, one that specifies the destination URL for the copied file, and the other a Boolean value that specifies whether to overwrite any file of the same name that is located at the destination.

Move Files in SharePoint:

SPWeb mySite = SPContext.Current.Web;

SPFolder myFolder = mySite.GetFolder("MySourceFolder");

SPFileCollection myFiles = myFolder.Files;

for (int i = myFiles.Count - 1; i > -1; i--)
{

    myFiles[i].MoveTo("MyDestinationFolder/" + myFiles[i].Name, true);

}

Here MoveTo also has parameter as true, which indicates it will overrite any files as the same name.

No comments:

Post a Comment