0

I am uploading files to dropbox using the following code.

I am using the nuget package Dropbox.Api and getting the exception System.Threading.Tasks.TaskCanceledException("A task was canceled.")

From this SO Question it appears to be a timeout issue.

So how do I modify the following code to set the timeout.

    public async Task<FileMetadata> UploadFileToDropBox(string fileToUpload, string folder)
    {
        DropboxClient client = new DropboxClient(GetAccessToken());

        using (var mem = new MemoryStream(File.ReadAllBytes(fileToUpload)))
        {
            string filename = Path.GetFileName(fileToUpload);

            try
            {
                string megapath = GetFullFolderPath(folder);
                string megapathWithFile = Path.Combine(megapath, Path.GetFileName(Path.GetFileName(filename))).Replace("\\", "/");
                var updated = client.Files.UploadAsync(megapathWithFile, WriteMode.Overwrite.Instance, body: mem);
                await updated;
                return updated.Result;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
Community
  • 1
  • 1
VivekDev
  • 20,868
  • 27
  • 132
  • 202

2 Answers2

6

Try creating and initializing the client like this:

var config = new DropboxClientConfig();
config.HttpClient.Timeout = new TimeSpan(hr, min, sec); // choose values
var client = DropboxClient(GetAccessToken(), config);

Reference:
http://dropbox.github.io/dropbox-sdk-dotnet/html/M_Dropbox_Api_DropboxClient__ctor_1.htm

Peter B
  • 22,460
  • 5
  • 32
  • 69
  • 3
    Hi Peter, Thank You. Its working. I had to add the following line as the second line config.HttpClient = new System.Net.Http.HttpClient(); as HttpClient obj is null. – VivekDev Nov 09 '16 at 09:40
  • Does any part of the Dropbox API expose a factory method for constructing the new HttpClient? I had the same problem as @VivekDev but am unsure that calling new HttpClient() is missing some other configuration steps that the Dropbox API might call internally if left to create the object itself. – Jono Nov 13 '16 at 09:58
  • @Jono no factory method, if you will not provide webClient in config, default one will be used https://github.com/dropbox/dropbox-sdk-dotnet/blob/28233d643ddc65660c565d2c23bed46cdd6af84a/Dropbox.Api/DropboxRequestHandler.cs#L57 – Sergey Tihon Mar 30 '17 at 14:43
0

One more thing to keep in mind is UploadAsync will not work for files larger than 150MB as per documentation. One will have to use UploadSessionStartAsync based implementation for it. I was making the mistake without realizing it and it took ages for me to fish the problem out.

sameerfair
  • 406
  • 7
  • 13