Wednesday, 20 November 2019

CSOM: How to copy all files from one SharePoint library to another?

private void btnCopyFiles_Click(object sender, EventArgs e)
        {
            int itemProcessed = 0;
            try
            {
                F.MessageBox.Show("Please make sure the workflows are disabled on the target list.");
                progressBar1.Value = 0;


                PnP.AuthenticationManager authManagerTarget = new PnP.AuthenticationManager();
                using (ClientContext clientContextTarget = authManagerTarget.GetWebLoginClientContext(txtTargetSite.Text))
                {
                    clientContextTarget.RequestTimeout = 9999999;
                    List targetList = clientContextTarget.Web.Lists.GetByTitle(drpTargetList.SelectedItem.ToString());
                    clientContextTarget.Load(targetList);
                    clientContextTarget.ExecuteQueryRetry();

                    PnP.AuthenticationManager authManagerSource = new PnP.AuthenticationManager();
                    using (ClientContext clientContextSource = authManagerSource.GetWebLoginClientContext(txtSourceSite.Text))
                    {
                        List sourceList = clientContextSource.Web.Lists.GetByTitle(drpSourceList.SelectedItem.ToString());
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml = "<View Scope ='RecursiveAll'></View>";
                        ListItemCollection sourceItems = sourceList.GetItems(camlQuery);
                        clientContextSource.Load(sourceItems);
                        clientContextSource.ExecuteQueryRetry();

                        progressBar1.Maximum = sourceItems.Count;


                        int itemToSkip = 0;
                        try
                        {
                            itemToSkip = txtItemsToSkip.Text.ToInt32();
                        }
                        catch { }

                        string sourceLibrary = string.Empty;
                        string targetLibrary = drpTargetList.SelectedItem.ToString();
                        string fileName = string.Empty;
                        string fileUrl = string.Empty;
                        string folderPath = string.Empty;
                        Web targetWeb = clientContextTarget.Web;
                        clientContextTarget.Load(targetWeb, u => u.ServerRelativeUrl);
                        clientContextTarget.ExecuteQueryRetry();
                        string _path = targetWeb.ServerRelativeUrl;

                        try
                        {
                            sourceLibrary = sourceItems[0].FieldValues["FileDirRef"].ToString();
                            string[] urlArr = sourceLibrary.Split('/');
                            sourceLibrary = urlArr[urlArr.Count() - 1];
                        }
                        catch { }

                        foreach (ListItem sourceItem in sourceItems)
                        {
                            itemProcessed++;

                            if (itemProcessed <= txtItemsToSkip.Text.ToInt32())
                            {
                                progressBar1.Value += 1;
                                continue;
                            }

                            if (sourceItem.FileSystemObjectType == FileSystemObjectType.File)
                            {
                                try
                                {
                                    fileUrl = sourceItem["FileRef"].ToString();
                                    if (!FileExists(targetList, fileUrl.Replace("/Shared Documents/","/Documents/")))
                                    {
                                        string[] fileNames = fileUrl.Split(new string[] { sourceLibrary }, StringSplitOptions.None);
                                        fileName = fileNames[fileNames.Count() - 1];

                                        MSC.File file = sourceItem.File;
                                        clientContextSource.Load(file);
                                        clientContextSource.ExecuteQueryRetry();

                                        FileInformation fileInfo = MSC.File.OpenBinaryDirect(clientContextSource, file.ServerRelativeUrl);
                                        MSC.File.SaveBinaryDirect(clientContextTarget, _path + "/" + targetLibrary + fileName, fileInfo.Stream, false);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.LogCopyError(ex, "File", targetLibrary, fileUrl);
                                }
                            }

                            else if (sourceItem.FileSystemObjectType == FileSystemObjectType.Folder)
                            {
                                try
                                {
                                    folderPath = sourceItem["FileRef"].ToString();
                                    string[] fileNames = folderPath.Split(new string[] { sourceLibrary }, StringSplitOptions.None);
                                    folderPath = fileNames[fileNames.Count() - 1];
                                    folderPath = folderPath.TrimStart(new Char[] { '/' });
                                    MSC.Folder folder = CreateFolder(clientContextTarget.Web, drpTargetList.SelectedItem.ToString(), folderPath);
                                }
                                catch (Exception ex)
                                {
                                    this.LogError(ex);
                                }
                            }

                            progressBar1.Value += 1;
                        }
                    }
                }
                F.MessageBox.Show("Done. Please match the items count");
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                F.MessageBox.Show("Something went wrong. Please check the logs.");
                try
                {
                    F.MessageBox.Show("Items processed: " + (--itemProcessed));
                }
                catch { }
            }
        }

        private MSC.Folder CreateFolder(Web web, string listTitle, string fullFolderPath)
        {

            if (string.IsNullOrEmpty(fullFolderPath))
                throw new ArgumentNullException("fullFolderPath");
            var list = web.Lists.GetByTitle(listTitle);
            return CreateFolderInternal(web, list.RootFolder, fullFolderPath);

        }

        private MSC.Folder CreateFolderInternal(Web web, MSC.Folder parentFolder, string fullFolderPath)
        {

            var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string folderUrl = folderUrls[0];
            var curFolder = parentFolder.Folders.Add(folderUrl);
            web.Context.Load(curFolder);
            web.Context.ExecuteQueryRetry();

            if (folderUrls.Length > 1)
            {
                var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
                return CreateFolderInternal(web, curFolder, folderPath);
            }

            return curFolder;
        }

        public bool FileExists(List list, string fileUrl)
        {
            var ctx = list.Context;
            var qry = new CamlQuery();
            qry.ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FileRef\"/><Value Type=\"Url\">{0}</Value></Eq></Where></Query></View>", fileUrl);
            var items = list.GetItems(qry);
            ctx.Load(items);
            ctx.ExecuteQuery();
            return items.Count > 0;
        }

Reference: https://sharepoint.stackexchange.com/a/203283

No comments:

Post a Comment