Wednesday, February 13, 2019

Copying folder library to another library (SharePoint 2010, 2013, 2016)

In this article, I continue to lay out the basic operations for working with .NET MS SharePoint server On-Premises one of which is copying a folder from an attachment inside from one library to another, as always I run the code from the Console application from Visual studio.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using Microsoft.SharePoint;

using (SPSite SPsite = new SPSite("http://sp/sites/test"))
            {
                using (SPWeb SPWeb = SPsite.OpenWeb())
                {
                    SPDocumentLibrary srcLib = (SPDocumentLibrary)SPWeb.Lists["Documents"];
                    SPDocumentLibrary destLib = (SPDocumentLibrary)SPWeb.Lists["OldDocuments"];
                    foreach (SPListItem sourceItem in srcLib.Folders)
                    {
                        SPFolder sourceFolder = sourceItem.Folder;
                        string targetPath = destLib.RootFolder.ServerRelativeUrl + "/" + sourceFolder.Name;
                        SPFolder targetFolder = SPWeb.GetFolder(targetPath);
                        SPListItem targetItem = targetFolder.Item;
                        sourceItem.Folder.CopyTo(targetPath);
                    }
               }
           }
Happy Coding!

No comments:

Post a Comment