Navigation

Saturday 21 January 2023

Dropbox API: How to download/upload file with Dropbox API

 Step 1: Start by Creating an app as shown in the below image.

Step 2: Give a name to an app like 'TestApp1205' and choose the scope of access as shown in the below image.

Step 3: After selecting an access scop, you have to generate an access token, through which you can get access to the app file and folder. 



Step 4: When the app has been created it looks like this.




Step 5: When file is uploaded with the help of code it looks like the below image.



Step 6: Following are the C# codes to download/upload files.


using Dropbox.Api;
using Dropbox.Api.Files;
using ExcelDataReader;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DropBoxApp
{
    class Program
    {
        public static StreamWriter log;
        //public static string localFilePath = "";

        static void Main(string[] args)
        {
            //localFilePath = Path.GetFullPath("../../../Test");
            Program program = new Program();
            var task = Task.Run((Func<Task>)program.Run);
            task.Wait();          
            Console.WriteLine("Hello World!");
        }
        public async Task Run()
        {

            using (var dbx = new DropboxClient("6exx-HrLsAxxxxTxmSHqbft_YR2Z6xxxxy5GKyHkR4KOM4_w2pGz"))
            {
                log = File.AppendText("logger");
                var full = await dbx.Users.GetCurrentAccountAsync();
                Console.WriteLine("D  {0}", full.Name.DisplayName + "-" + full.Email);
                ListRootFolder(dbx).Wait();
               
            }
        }
      public  async Task ListRootFolder(DropboxClient dbx)
        {
            var list = await dbx.Files.ListFolderAsync(string.Empty);

            // show folders then files
            foreach (var item in list.Entries.Where(i => i.IsFolder))
            {
                Console.WriteLine("D  {0}/", item.Name);
            }
            foreach (var item in list.Entries.Where(i => i.IsFile))
            {
                Console.WriteLine("F{0,8} {1}", item.AsFile.Size, item.Name);
                Download(dbx,"", item.Name).Wait();
            }
        }

     public  async Task Download(DropboxClient dbx, string folder, string file)
        {
            Console.WriteLine("Download file...");

            using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
            {
                Stream StreamFromDropbox = await response.GetContentAsStreamAsync();
                System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
                MemoryStream StreamFromDropboxCopyAsync = new MemoryStream();
                await StreamFromDropbox.CopyToAsync(StreamFromDropboxCopyAsync);
                StreamFromDropboxCopyAsync.Seek(offset: 0, loc: SeekOrigin.Begin);
                IExcelDataReader reader = ExcelDataReader.ExcelReaderFactory
.CreateOpenXmlReader(StreamFromDropboxCopyAsync,
new ExcelReaderConfiguration()
{ FallbackEncoding = System.Text.Encoding.GetEncoding(1252) });
               
                //Value store in dataset
                DataSet ds = reader.AsDataSet();

                Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev);

                //Console.WriteLine("------------------------------");
                //Console.WriteLine(await response.GetContentAsStringAsync());
                //Console.WriteLine("------------------------------");
            }          
           
        }

       //public async Task Upload(DropboxClient dbx, string folder, string file, string content)
       // {
       //     using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
       //     {
       //         var updated = await dbx.Files.UploadAsync(
       //             folder + "/" + file,
       //             WriteMode.Overwrite.Instance,
       //             body: mem);
       //         Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
       //     }
       // }
    }
}


Some other methods to call Dropbox API 

using Dropbox.Api;
using Dropbox.Api.Common;
using Dropbox.Api.Files;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace DropBoxApp
{
    class Program
    {
        public static StreamWriter log;
        //public static string localFilePath = "";

        static void Main(string[] args)
        {
            //localFilePath = Path.GetFullPath("../../../Test");
            Program program = new Program();
            var task = Task.Run((Func<Task>)program.Run);
            task.Wait();          
            Console.WriteLine("Hello World!");
        }
        private async Task<FolderMetadata> CreateFolder(DropboxClient client, string path)
        {
            Console.WriteLine("--- Creating Folder ---");
            var folderArg = new CreateFolderArg(path);
            try
            {
                var folder = await client.Files.CreateFolderV2Async(folderArg);

                Console.WriteLine("Folder: " + path + " created!");

                return folder.Metadata;
            }
            catch (ApiException<CreateFolderError> e)
            {
                if (e.Message.StartsWith("path/conflict/folder"))
                {
                    Console.WriteLine("Folder already exists... Skipping create");
                    return null;
                }
                else
                {
                    throw e;
                }
            }
        }

        public async Task Run()
        {

            using (var dbx = new DropboxClient("6exx-HrLsAxxxxTxmSHqbft_YR2Z6xxxxy5GKyHkR4KOM4_w2pGz"))
            {
                log = File.AppendText("logger");
                await  GetCurrentAccount(dbx);
                //var full = await dbx.Users.GetCurrentAccountAsync();
                //Console.WriteLine("D  {0}", full.Name.DisplayName + "-" + full.Email);
                //ListRootFolder(dbx).Wait();

                var path = "/EventId";
                var folder = await CreateFolder(dbx, path);
                var list = await ListFolder(dbx, path);

                var firstFile = list.Entries.FirstOrDefault(i => i.IsFile);
                if (firstFile != null)
                {
                    await Download(dbx, path, firstFile.AsFile);
                }
                //var pathInTeamSpace = "/Test";
                //await ListFolderInTeamSpace(dbx, pathInTeamSpace);                
                await Upload(dbx, path, firstFile.AsFile, "This is a text file");
                //await ChunkUpload(dbx, path, "Binary");

            }
        }
        private async Task GetCurrentAccount(DropboxClient client)
        {
            var full = await client.Users.GetCurrentAccountAsync();

            Console.WriteLine("Account id    : {0}", full.AccountId);
            Console.WriteLine("Country       : {0}", full.Country);
            Console.WriteLine("Email         : {0}", full.Email);
            Console.WriteLine("Is paired     : {0}", full.IsPaired ? "Yes" : "No");
            Console.WriteLine("Locale        : {0}", full.Locale);
            Console.WriteLine("Name");
            Console.WriteLine("  Display  : {0}", full.Name.DisplayName);
            Console.WriteLine("  Familiar : {0}", full.Name.FamiliarName);
            Console.WriteLine("  Given    : {0}", full.Name.GivenName);
            Console.WriteLine("  Surname  : {0}", full.Name.Surname);
            Console.WriteLine("Referral link : {0}", full.ReferralLink);

            if (full.Team != null)
            {
                Console.WriteLine("Team");
                Console.WriteLine("  Id   : {0}", full.Team.Id);
                Console.WriteLine("  Name : {0}", full.Team.Name);
            }
            else
            {
                Console.WriteLine("Team - None");
            }
        }
        //private async Task RunUserTests(DropboxClient client)
        //{
        //    await GetCurrentAccount(client);

        //    //var path = "/DotNetApi/Help";
        //    //var folder = await CreateFolder(client, path);
        //    //var list = await ListFolder(client, path);

        //    //var firstFile = list.Entries.FirstOrDefault(i => i.IsFile);
        //    //if (firstFile != null)
        //    //{
        //    //    await Download(client, path, firstFile.AsFile);
        //    //}

        //    //var pathInTeamSpace = "/Test";
        //    //await ListFolderInTeamSpace(client, pathInTeamSpace);

        //    //await Upload(client, path, "Test.txt", "This is a text file");

        //    //await ChunkUpload(client, path, "Binary");
        //}
        //public  async Task ListRootFolder(DropboxClient dbx)
        //{
        //    var list = await dbx.Files.ListFolderAsync(string.Empty);

        //    // show folders then files
        //    foreach (var item in list.Entries.Where(i => i.IsFolder))
        //    {
        //        Console.WriteLine("D  {0}/", item.Name);
        //    }
        //    foreach (var item in list.Entries.Where(i => i.IsFile))
        //    {
        //        Console.WriteLine("F{0,8} {1}", item.AsFile.Size, item.Name);
        //        //Download(dbx,"", item.Name).Wait();
        //    }
        //}
        private async Task<ListFolderResult> ListFolder(DropboxClient client, string path)
        {
            Console.WriteLine("--- Files ---");
            var list = await client.Files.ListFolderAsync(path);

            // show folders then files
            foreach (var item in list.Entries.Where(i => i.IsFolder))
            {
                Console.WriteLine("D  {0}/", item.Name);
            }

            foreach (var item in list.Entries.Where(i => i.IsFile))
            {
                var file = item.AsFile;

                Console.WriteLine("F{0,8} {1}",
                    file.Size,
                    item.Name);
            }

            if (list.HasMore)
            {
                Console.WriteLine("   ...");
            }
            return list;
        }
        private async Task Download(DropboxClient client, string folder, FileMetadata file)
        {
            Console.WriteLine("Download file...");

            using (var response = await client.Files.DownloadAsync(folder + "/" + file.Name))
            {
                Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev);
                Console.WriteLine("------------------------------");
                Stream StreamFromDropbox = await response.GetContentAsStreamAsync();
                SaveFileStream(folder, StreamFromDropbox, response.Response.Name);
                Console.WriteLine("------------------------------");
            }
        }
        private void SaveFileStream(string path, Stream stream,string fileName)
        {
            string localFilePath = Path.GetFullPath("../../../"+path+"/"+fileName);
            var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
            stream.CopyTo(fileStream);
            fileStream.Dispose();
        }
        private async Task Upload(DropboxClient client, string folder, FileMetadata file, string fileContent)
        {
            Console.WriteLine("Upload file...");
            string NewFileName = DateTime.Now.ToString("ddMMyyyymmss") + "_" + file.Name;
            string str = folder + "/" + NewFileName;
           
            string localFilePath = Path.GetFullPath("../../../EventId/" + file.Name);

            FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
            byte[] tmpBytes = new byte[fs.Length];
            fs.Read(tmpBytes, 0, Convert.ToInt32(fs.Length));
            //MemoryStream mystream = new MemoryStream(tmpBytes);

            using (var stream = new MemoryStream(tmpBytes))
            {
                var response = await client.Files.UploadAsync(folder + "/" + NewFileName, WriteMode.Overwrite.Instance, body: stream);

                Console.WriteLine("Uploaded Id {0} Rev {1}", response.Id, response.Rev);
            }
        }
        private async Task ChunkUpload(DropboxClient client, string folder, string fileName)
        {
            Console.WriteLine("Chunk upload file...");
            // Chunk size is 128KB.
            const int chunkSize = 128 * 1024;

            // Create a random file of 1MB in size.
            var fileContent = new byte[1024 * 1024];
            new Random().NextBytes(fileContent);

            using (var stream = new MemoryStream(fileContent))
            {
                int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize);

                byte[] buffer = new byte[chunkSize];
                string sessionId = null;

                for (var idx = 0; idx < numChunks; idx++)
                {
                    Console.WriteLine("Start uploading chunk {0}", idx);
                    var byteRead = stream.Read(buffer, 0, chunkSize);

                    using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead))
                    {
                        if (idx == 0)
                        {
                            var result = await client.Files.UploadSessionStartAsync(body: memStream);
                            sessionId = result.SessionId;
                        }

                        else
                        {
                            UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx));

                            if (idx == numChunks - 1)
                            {
                                await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream);
                            }

                            else
                            {
                                await client.Files.UploadSessionAppendV2Async(cursor, body: memStream);
                            }
                        }
                    }
                }
            }
        }
        private async Task ListFolderInTeamSpace(DropboxClient client, string path)
        {
            // Fetch root namespace info from user's account info.
            var account = await client.Users.GetCurrentAccountAsync();

            if (!account.RootInfo.IsTeam)
            {
                Console.WriteLine("This user doesn't belong to a team with shared space.");
            }
            else
            {
                try
                {
                    // Point path root to namespace id of team space.
                    client = client.WithPathRoot(new PathRoot.Root(account.RootInfo.RootNamespaceId));
                    await ListFolder(client, path);
                }
                catch (PathRootException ex)
                {
                    Console.WriteLine(
                        "The user's root namespace ID has changed to {0}",
                        ex.ErrorResponse.AsInvalidRoot.Value);
                }
            }
        }

        //public async Task Download(DropboxClient dbx, string folder, string file)
        //{
        //    Console.WriteLine("Download file...");

        //    using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
        //    {
        //        Stream StreamFromDropbox = await response.GetContentAsStreamAsync();
        //        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        //        MemoryStream StreamFromDropboxCopyAsync = new MemoryStream();
        //        await StreamFromDropbox.CopyToAsync(StreamFromDropboxCopyAsync);
        //        StreamFromDropboxCopyAsync.Seek(offset: 0, loc: SeekOrigin.Begin);
        //        IExcelDataReader reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(StreamFromDropboxCopyAsync, new ExcelReaderConfiguration() { FallbackEncoding = System.Text.Encoding.GetEncoding(1252) });

        //        //Value store in dataset
        //        DataSet ds = reader.AsDataSet();

        //        Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev);

        //        //Console.WriteLine("------------------------------");
        //        //Console.WriteLine(await response.GetContentAsStringAsync());
        //        //Console.WriteLine("------------------------------");
        //    }

        //    //using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
        //    //{
        //    //     string _file = await response.GetContentAsStringAsync();

        //    //    //Console.WriteLine(await response.GetContentAsStringAsync());
        //    //}
        //}

        //public async Task Upload(DropboxClient dbx, string folder, string file, string content)
        // {
        //     using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
        //     {
        //         var updated = await dbx.Files.UploadAsync(
        //             folder + "/" + file,
        //             WriteMode.Overwrite.Instance,
        //             body: mem);
        //         Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
        //     }
        // }
    }
}

No comments:

Post a Comment