1

How do I copy all items from one folder(include sub folders and all files) to another folder or location?

I have to copy all items to one folder another folder by using C#

2

2 Answers 2

4

The following example could be used as a starting point:

    public static void CopyFiles(string url, string listTitle, string srcFolder,string destFolder)
    {
        using (var context = new ClientContext(url))
        {
            //context.Credentials = credentials;


            var srcList = context.Web.Lists.GetByTitle(listTitle);
            var qry = CamlQuery.CreateAllItemsQuery();
            qry.FolderServerRelativeUrl = string.Format("/{0}", srcFolder);
            var srcItems = srcList.GetItems(qry);
            context.Load(srcItems, icol => icol.Include(i => i.FileSystemObjectType, i => i["FileRef"], i => i.File));
            context.ExecuteQuery();

            foreach (var item in srcItems)
            {
                switch (item.FileSystemObjectType)
                {
                    case FileSystemObjectType.Folder:
                        var destFolderUrl = ((string)item["FileRef"]).Replace(srcFolder,destFolder);
                        CreateFolder(context.Web,destFolderUrl);
                        break;
                    case FileSystemObjectType.File:
                        var destFileUrl = item.File.ServerRelativeUrl.Replace(srcFolder, destFolder);
                        item.File.CopyTo(destFileUrl, true);
                        context.ExecuteQuery();
                        break;
                }
            }
        }
    } 

    private static Folder CreateFolder(Web web, string folderUrl)
    {
        if (string.IsNullOrEmpty(folderUrl))
            throw new ArgumentNullException("Folder Url could not be empty");

        var folder = web.Folders.Add(folderUrl);
        web.Context.Load(folder);
        web.Context.ExecuteQuery();
        return folder;
    }

Usage

CopyFiles("https://contoso.sharepoint.com/", "Order Documents", "Archive", "Archive 2014");

Key points:

  • It is assumed that destination folders do not exist
0

If you do not insist on preserving some metadata (created date, created by etc.) you can copy files using file explorer.

Or if it is only one-time task, try Sharegate (trial) to move the files.

1
  • 2
    OP is asking for a solution using CSOM.
    – Nick Cox
    Commented Nov 19, 2014 at 0:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.