Tuesday, February 5, 2013

Download files from Sharepoint Library Recursively

Hi
This is a small program that will download the contents of a Sharepoint documnt library.

This will download all the files in the subfolders as well

class Program
{
 static void Main(string[] args)
 {
  Console.WriteLine("This Application will download the documents in a library");
  Console.Write("Enter Site URL : ");
  string SiteURL = Console.ReadLine();

  Console.Write("Library Name : ");
  string LibraryName = Console.ReadLine();

  //Open the site using the given url
  using (SPSite site = new SPSite(SiteURL))
  {
   //Open the web application
   using (SPWeb web = site.OpenWeb())
   {
    try
    {
     //Get the library folder
     SPFolder folder = web.GetFolder(LibraryName);

     //Download files
     downloadFilesrecursively(folder);
    }
    catch (Exception ex)
    {
     //Print the details of the exception
     Console.WriteLine("An Error Occured while processing " + ex.Message);
    }
   }
  }

  Console.ReadLine();
 }

 //The method that downloads the files from a given SPFolder
 public static void downloadFiles(SPFolder folder)
 {
  foreach (SPFile item in folder.Files)
  {
   //Download the file
   byte[] fileData = item.OpenBinary();
   System.IO.FileStream fstream = System.IO.File.Create(item.Name);
   fstream.Write(fileData, 0, fileData.Length);
   Console.WriteLine(item.Name + " " + fileData.Length);
  }
 }

 //Method that is used to call the download method recursively
 public static void downloadFilesrecursively(SPFolder folder)
 {
  //If the folder have subfolders call the download
  //Methods for the subfolders
  if (folder.SubFolders.Count != 0)
  {
   //Download the files in the current folder
   downloadFiles(folder);
   foreach (SPFolder item in folder.SubFolders)
   {
    downloadFilesrecursively(item);
   }
  }
  else
  {
   //If the folder has no subfolders
   //then download the file in the folder
     downloadFiles(folder);   
  }
 }
}

No comments:

Post a Comment