Move a document within a Site Collection in SharePoint Office 365 using C# Patterns and Practices

Sathish Nadarajan
SharePoint MVP
Published On :   18 Jun 2017
Visit Count
Today :  2    Total :   2311

Today, I met with a requirement to move the documents from one Document Library to another Document Library. It is a kind of event receiver, which we need to do from a Console application. It was a one line code, which will move from the Source Document Library to Target Document Library along with the Metadata Information as well. It is really a single line of code to do this. Hence, thought of making it handy to the community.

The Scenario is, I have a Site Collection with two Document Libraries.

1. MySourceDocLib

2. MyTargetDocLib

The File from Source Doc Lib needs to be moved to the Target Doc Lib with the Metadata. Both the Libraries are having a Content Type MyContentType.

 using Microsoft.SharePoint.Client;
 using OfficeDevPnP.Core.Framework.Provisioning.Connectors;
 using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml;
 using System.IO;
 using System.Net;
 using System.Text;
 namespace Office365.Console
     class Program
         static void Main(string[] args)
         public static void MoveDocumentBetweenLibraries()
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
             string siteUrl = "https://*******";
             string userName = "Sathish@*****";
             string password = "***********";
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 Web web = clientContext.Web;
                 List sourceList = web.Lists.GetByTitle("MySourceDocLib");
 //As an example, I am taking a Document with the ID 3.  This depends on the requirement.
                 ListItem listItem = sourceList.GetItemById(3);
                 listItem.File.MoveTo("https://*****", MoveOperations.Overwrite);

And one interesting thing is, even if the Target Library does not have the Content Type, then the document is getting moved without the Metadata Information. That was really amazing!!!!

In the next article, let us see, how to move between Site Collections. That’s also an interesting Scenario. Let me explain the scenario and the solution in the next article.

Happy Coding,

Sathish Nadarajan.