Email: Password:       Forgot Password 
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.

Copy Files from document library to local in SharePoint

Viewed:  9163 
Posted On:  05/06/2013 10:25:46 
How to make a local copy of SharePoint Document library with the same structure as it have in Document Library? 

 In this article I am going to show how we can Copy files from SharePoint document library to local folder. 

My SharePoint site is
http://localhost:2000. And I want to make a local copy of SharePoint document library dotnetcodesg_Doclib. 

Below is the code: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Configuration;
using System.IO;
namespace DownloadDocumentLibrary
    class Program
        static void Main(string[] args)
            //document library name to download
            Console.WriteLine("All Files Ciopied Successfully.");
            Console.WriteLine("Press Enter To Exit...");
        static void DownloadFile(string DownloadLocation)
            SPWeb web = new SPSite("http://localhost:2000").OpenWeb();
            using (web)
                SPList list = web.Lists["dotnetcodesg_doclib"];
                SPFolderCollection folders = web.GetFolder(DownloadLocation).SubFolders;
                //location where Document library All files and folder will save.
                string FolderPath = @"F:\BKP\" + DownloadLocation;
                foreach (SPFolder oFolder1 in folders)
                    int len = oFolder1.ToString().LastIndexOf('/');
                    string folderName = oFolder1.ToString().Substring(len + 1);                   
                    if (!Directory.Exists(FolderPath + folderName))
                        Directory.CreateDirectory(FolderPath + folderName);
                    foreach (SPFile file in oFolder1.Files)
                        DownloadFileUsingFileStream(file, FolderPath + folderName + @"\");
                        Console.WriteLine(FolderPath + folderName + @"\");                                          
                    DownloadFile(DownloadLocation + folderName + @"\");
        //To Download File
        static void DownloadFileUsingFileStream(SPFile file, string path)
            byte[] filecontent = file.OpenBinary();
            FileStream fs = new FileStream(path + file.Name, FileMode.CreateNew);
            using (fs)
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(filecontent, 0, filecontent.Length);

         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us