I have to Download Root level folders, sub folders and all files using CSOM and C#.

I have to save the same folder structure and all file paths into the local system.

Please provide the solution for this.

  • You can do this without csom as well. – Unnie Jul 14 '14 at 18:58
  • 2
    Just a note for the future, the tone of your question makes it appear that you were given a task to do, posted that task here, and waited for someone to do the work for you (I realize that may not be the case). In the future it would be better if you showed what you had tried and where you had already looked for ways to solve your problem. That way it's clear that you have invested time already and are now looking for help in an area where you are stuck. – Rob Windsor Jul 11 '15 at 1:22

If you are using SharePoint 2013, then you can achieve this OOTB using Sync option in library. It will sync all your library files in the same folder structure specified in library to a local folder in your computer. See this blog for more details. Further see this to understand limitations of Syncing library to computer.

If you still want to implement it using CSOM C#. You can try below code as a starting point:

static void Main(string[] args)
            string siteUrl = "https://yoursiteurl.com";
            string userName = "user@tenant.onmicrosoft.com";
            string password = "password";
            using (ClientContext clientContext = new ClientContext(siteUrl))
                SecureString securePassword = new SecureString();

foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
            Web web = clientContext.Web;
            clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
            var list = clientContext.Web.Lists.GetByTitle("Documents");
            var rootFolder = list.RootFolder;
            string pathString=@"C:\Documents\";
            GetFoldersAndFiles(rootFolder, clientContext, pathString);



private static void GetFoldersAndFiles(Folder mainFolder, ClientContext clientContext,string pathString)
            clientContext.Load(mainFolder, k => k.Files, k => k.Folders);
            foreach (var folder in mainFolder.Folders)
                string folderPath = string.Format(@"{0}\{1}",pathString,folder.Name);

                GetFoldersAndFiles(folder, clientContext, folderPath);

            foreach (var file in mainFolder.Files)
                var fileRef = file.ServerRelativeUrl;
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
                var fileName = Path.Combine(pathString,file.Name);
                using (var fileStream = System.IO.File.Create(fileName))




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.