Sharepoint CSOM copy (move), delete and update files from one site collection to another

 

Here is a code sample on how to copy a file from one site collection to another one. Also how to update a file uploaded in the target destination and how to remove it from the source location.


private static void CheckWorkspaceForDocumentsToBeArhieved(String workspaceURL, string recordCenterURL)
 {
 Console.WriteLine("UpdateStatusOnMetadataPageOnWorkspace");
 Uri siteUrl = new Uri(workspaceURL);
 Uri recordCenterUrl = new Uri(recordCenterURL);
 string realm = TokenHelper.GetRealmFromTargetUrl(siteUrl);
 var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUrl.Authority, realm).AccessToken;
 using (var ctxWorkspace = TokenHelper.GetClientContextWithAccessToken(siteUrl.ToString(), token))
 {
 string realmRC = TokenHelper.GetRealmFromTargetUrl(recordCenterUrl);
 var tokenRC = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, recordCenterUrl.Authority, realm).AccessToken;
 using (var ctxWorkspaceRC = TokenHelper.GetClientContextWithAccessToken(recordCenterUrl.ToString(), token))
 {
 ListCollection lists = ctxWorkspace.Web.Lists;
 var sourceWeb = ctxWorkspace.Web;
 ctxWorkspace.Load(sourceWeb);
 ctxWorkspace.Load(lists);
 ctxWorkspace.ExecuteQuery();

 foreach (List list in lists.Where(o => o.BaseType == BaseType.DocumentLibrary))
 {
 if (list.Hidden || list.IsApplicationList || list.IsCatalog)
 continue;

 if (!list.FieldExistsByName("Archieve") && !list.FieldExistsByName("Secret"))
 continue;

 Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
 camlQuery.ViewXml = @"<View Scope='RecursiveAll'><Query><Where>
 <Eq>
 <FieldRef Name='Archieve' />
 <Value Type='Boolean'>1</Value>
 </Eq>
 </Where>
 <ViewFields>
 <FieldRef Name='Archieve' />
 <FieldRef Name='FileRef' />
 <FieldRef Name='Secret' />
 <FieldRef Name='LinkFilename' />
 <FieldRef Name='Title' />
 </ViewFields></Query></View>";

 var documents = list.GetItems(camlQuery);
 ctxWorkspace.Load(documents);
 ctxWorkspace.ExecuteQuery();
List<int> filesToRemove = new List<int>();

 foreach (ListItem document in documents)
 {
 
 

 var file = document.File;
 ctxWorkspace.Load(document);
 ctxWorkspace.Load(file);
 var fileStream = file.OpenBinaryStream();
 ctxWorkspace.ExecuteQuery();

 var isSecret = document.FieldValues.SingleOrDefault(o => o.Key.Contains("Secret"));

 bool isSecretDocument = false;
 if(isSecret.Value != null)
 isSecretDocument = (bool)isSecret.Value;


 FileCreationInformation fci = new FileCreationInformation();

  using (var streamReader = new MemoryStream())
 {

 fileStream.Value.CopyTo(streamReader);
 // This step is done to avoid an error with the copying the data to the target location 
 streamReader.Seek(0, System.IO.SeekOrigin.Begin);
 // This variable is used in FileCreationInformation to avoid too large files data problem. More info: https://msdn.microsoft.com/en-us/library/office/dn904536.aspx
 fci.ContentStream = streamReader;
 
 
 fci.Url = file.Name;
 fci.Overwrite = true;
 List targetLibrary = null;

 if (isSecretDocument)
 {
 targetLibrary = ctxWorkspaceRC.Web.Lists.GetByTitle("Secret");
 
 }
 else
 {

 targetLibrary = ctxWorkspaceRC.Web.Lists.GetByTitle("Public");
 }

 ctxWorkspaceRC.Load(targetLibrary);
 ctxWorkspaceRC.ExecuteQuery();
 var folder = targetLibrary.RootFolder.EnsureFolder("folder name");

 ctxWorkspaceRC.Load(folder);
 var uploadedFile = targetLibrary.RootFolder.Files.Add(fci);
 ctxWorkspaceRC.Load(uploadedFile, f => f.ListItemAllFields);
 ctxWorkspaceRC.ExecuteQuery();

 var newDocumentItemInTargetLibrary = targetLibrary.GetItemById(uploadedFile.ListItemAllFields.Id);
 ctxWorkspaceRC.Load(newDocumentItemInTargetLibrary);
 ctxWorkspaceRC.ExecuteQuery();

 newDocumentItemInTargetLibrary["field to update"] = sourceWeb.Title;
 newDocumentItemInTargetLibrary["field to update"] = sourceWeb.Description;
 newDocumentItemInTargetLibrary.Update();
if(uploadedFile.CheckOutType != CheckOutType.None)
   uploadedFile.CheckIn("custom operation", CheckinType.MajorCheckIn);
 ctxWorkspaceRC.ExecuteQuery();

 filesToRemove.Add(document.Id);
}

 }
foreach(int fileItemID in filesToRemove)
 {
 for (int x = documents.Count - 1; x >= 0; x-- )
 {
 if (documents[x].Id == fileItemID)
 {
 documents[x].DeleteObject();
 }
 }
 }
 ctxWorkspace.ExecuteQuery();

 }
 }
 }
 }

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