SharePoint: Copy Folder and Files Recursively from Source to Destination Document library

Here is the code snippet that copies the entire content of a folder in from a source list/Document library to the destination FOlder in a source list/Document library. The Destination List can on other Site collection. This is server side code so it does not matter at long as appropriate permissions are in place the permission are elevated. Using this code an entire document library can also be copied to another one.
So here goes the code:

private void CopyFolderFilesRecursively(SPList objSourceList, SPFolder objSourceFolder, SPFolder objDestinationFolder)
        {
            SPListItemCollection objItems = ((SPDocumentLibrary)objSourceList).GetItemsInFolder(objSourceList.DefaultView, objSourceFolder);
            foreach (SPListItem objItem in objItems)
            {
                if (objItem.FileSystemObjectType == SPFileSystemObjectType.File)
                {
                    byte[] fileBytes = objItem.File.OpenBinary();
                    string DestinationURL = string.Format(@"{0}/{1}", objDestinationFolder.Url, objItem.File.Name);
                    SPFile objDestinationFile = objDestinationFolder.Files.Add(DestinationURL, fileBytes, false);
                    objDestinationFile.Update();
                }
                else
                {
                    string dirURL = string.Format(@"{0}/{1}", objDestinationFolder.Url, objItem.Folder.Name);
                    if (!objSourceFolder.Name.Contains("Forms"))
                    {
                        SPFolder objNewFolder = objDestinationFolder.SubFolders.Add(dirURL);
                        objNewFolder.Update();
                        CopyFolderFilesRecursively(objSourceList, objItem.Folder, objNewFolder);
                    }
                }
            }
        }


Disclaimer: I don't own this code niether did I write it, so please try it at your own risk.

Comments

Popular posts from this blog

SPFx: Develop using SharePoint Framework without Installing all the dependecies.

SharePoint Online: Elevated Permissions....with love

Powershell: Filling up an Existing Excel Sheet with data from SQL Server