Move documents from one Document Library to another programmatically in SharePoint 2007

By Jatin Prajapati

In this FAQ we will see how to move documents from one document library to another using code in SharePoint 2007.

Many of us have requirements that, we need a way to move or copy some or all the documents from one document library to another document library programmatically. So, following code sample show you how to achieve this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.SharePoint;

namespace Jatin
{
    public class MoveCopyDocuments
    {
         public static void Main(string[] args)
        {
             MoveDocuments("My Documents", "Shared Documents", true);
        }

         private static void MoveDocuments(string fromDocName, string destinationDocName, bool bMove)
        {             
             using (SPSite site = new SPSite("http://invind106:18779"))
            {
                 using (SPWeb web = site.OpenWeb())
                {
                    SPList docLibSource = web.Lists[fromDocName];
                    SPListItemCollection items = docLibSource.Items;
                     foreach (SPListItem item in items)
                     {
                          if (item.File.Exists)
                         {
                              if (bMove)
                                  item.File.MoveTo(string.Format("{0}/{1}/{2}", web.Url, destinationDocName, item.File.Name), true);
                              else
                                  item.File.CopyTo(string.Format("{0}/{1}/{2}", web.Url, destinationDocName, item.File.Name), true);          
                          }
                      }
                     
                 }
             }
        }
    }
}

Move documents from one Document Library to another programmatically in SharePoint 2007  (1439 Views)