SharePoint SPFile : MoveTo and CopyTo method

In SharePoint, using object model, files can moved from one folder to another folder or one library to another library within the same site collection, For this, SPFile object has two methods :

  • MoveTo(string)
  • CopyTo(string)

SPFile.MoveTo(string destinationURL)

This method moves the original file with all metadata and version history from one location to another location by providing the destination url as a parameter.

SPWeb spWeb = SPContext.Current.Site.RootWeb;
SPFileCollection allFiles = spWeb.GetFolder("Source_Folder").Files;
for (int intIndex=allFiles.Count-1; intIndex>-1; intIndex--)
{
   allFiles[intIndex].MoveTo("Destination_Folder/" + allFiles[intIndex].Name);
}

 

SPFile.CopyTo(string destinationURL)

This method copies the original file with all metadata from one location to another location by providing the destination URL as a parameter.

SPWeb spWeb = SPContext.Current.Site.RootWeb;
SPFileCollection allFiles = spWeb.GetFolder("Source_Folder").Files;
for (int intIndex=allFiles.Count-1; intIndex>-1; intIndex--)
{
   allFiles[intIndex].CopyTo("Destination_Folder/" + allFiles[intIndex].Name);
}

 

Note : Both methods have one more overloaded method which accepts Boolean as parameter:

  • SPFile.MoveTo(string, boolean)
  • SPFile.CopyTo(string, boolean)

As per msdn, if this parameter is true then it will overwrite the existing file with same name in destination URL. But these methods work differently, if there is any existing file in destination URL then it is first deleted and moved to Recycle Bin and after that original file is moved or copied to destination URL.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s