Friday, 30 August 2013

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

http://www.fewlines4biju.com/2013/05/copy-or-move-files-from-one-folder-to.html

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