Box Developer Documentation

Download All Files in Folder using SDKs

Guides Downloads Download All Files in Folder using SDKs
Edit this page

Download All Files in Folder using SDKs

Sometimes an application might want to download all files for a folder. To do so with the SDKs and the CLI requires traversing the folder tree, finding every file and downloading it accordingly.

To download a ZIP archive, follow this guide.

.NET
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Box.V2.Config;
using Box.V2.JWTAuth;

namespace BoxDownloadAllFiles {
    class Program {
        static void Main (string[] args) {
            ExecuteMainAsync ().Wait ();
        }

        private static async Task ExecuteMainAsync () {
            using (FileStream fs = new FileStream ($"./config.json", FileMode.Open)) {
                var session = new BoxJWTAuth (BoxConfig.CreateFromJsonFile (fs));
                var client = session.AdminClient (session.AdminToken ());
                var folderId = "987654321";
                var folder = await client.FoldersManager.GetInformationAsync (folderId);
                var folderName = folder.Name;
                var localFolderPath = Path.Combine (Directory.GetCurrentDirectory (), folderName);
                ResetLocalFolder (localFolderPath);

                var items = await client.FoldersManager.GetFolderItemsAsync (folderId, 1000, autoPaginate : true);
                var fileDownloadTasks = new List<Task> ();
                var files = items.Entries.Where (i => i.Type == "file");
                foreach (var file in files) {
                    fileDownloadTasks.Add (client.FilesManager.DownloadStreamAsync (file.Id).ContinueWith ((t) => {
                        var localFile = File.Create (Path.Combine (localFolderPath, file.Name));
                        return t.Result.CopyToAsync (localFile);
                    }));
                }
                await Task.WhenAll (fileDownloadTasks);
            }
        }

        private static void ResetLocalFolder (string localFolderPath) {
            if (!Directory.Exists (localFolderPath)) {
                Directory.CreateDirectory (localFolderPath);
            } else {
                foreach (var file in Directory.EnumerateFiles (localFolderPath)) {
                    File.Delete (Path.Combine (localFolderPath, file));
                }
                Directory.Delete (localFolderPath);
                Directory.CreateDirectory (localFolderPath);
            }
        }
    }
}

It is important to remember that an application needs to have the permissions to access and download the files and folders in question. When the authenticated user does not have access to any of the files or folders, a HTTP 404 Not Found error will occur.

Lear more about User Types in our guides on authentication.