Friday 11 January 2013

Move Documents from one Library to Other in SharePoint 2010



The following code shows how to move documents from one Document Library to Other.

/// MoveToDocLib is a method to move Document from Source Library to Destination Library
/// <param name="siteUrl">Pass Site url of SiteCollection</param>
/// <param name="Source">Pass Source Library Name</param>
/// <param name="Destination">Pass Destination Library Name</param>

public void MoveToDocLib(string siteUrl, string Source, string Destination)
{
  SPQuery qry = new SPQuery();    //To query the item
  string camlquery = string.Empty;
  string destlibUrl = string.Empty;
  SPListItemCollection Srccollitem;
  SPList destlib;
  SPFile moveFile;
  try
  {
    using (SPSite rootSite = new SPSite(siteUrl)) //siteUrl is the URL of the site
    {
      using (SPWeb spWeb = rootSite.OpenWeb())
      {
        //The below query gets all the items whose Expiry Date column contains Date Today’s Date or previous date
        camlquery = "<Where>"
                     + "<Lt>"
                     + "<FieldRef Name='Expiry_x0020_Date' />"
                     + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                     + "</Lt>"
                     + "</Where>";
         qry.Query = camlquery;
         qry.ViewAttributes = "<View Scope=\'RecursiveAll\'>";
        ///Get the Collection of SourceLibraryDocument by Caml Query
        Srccollitem = spWeb.Lists[Source].GetItems(qry);

        ///Get the Destination Library
        destlib = (SPDocumentLibrary)spWeb.Lists[Destination];
        ///Get the URL of the Destination Library
        destlibUrl = destlib.RootFolder.Url;

        ///Start of ForEach Loop to Move Document one by one from Source Library to Destination Library.
        foreach (SPListItem item in Srccollitem)
        {
          moveFile = item.File;
          moveFile.MoveTo(destlibUrl + "/" + moveFile.Name, true);
        }
        ///End of ForEach Loop
      }
    }

  }
  catch (Exception ex)
  {

  }
          
}

No comments:

Post a Comment