Dropbox API, RestSharp and C# Part 2: The Revenge!

Posted by on

Open Source

Following on from my previous post where I showed you how to Login and get the Account Info for a Dropbox account. Today we dive into the Box full of files. Uploading, Downloading and Deleting!

A lot has changed since my last post in the way of RestSharp with OAuth. OAuth is now available Out-of-the-box (this can be downloaded from Github). Ok, Time for some code…

Download File:

Update: Fixed a bug in the code that only allowed for text based files to be downloaded. Using restClient.DownloadData now instead of Execute to get the response’s raw Data.

public byte[] DownloadFile(string path)
{
    var restClient = new RestClient("http://api-content.dropbox.com");
    //load the JsonDeserializer for all types
    restClient.ClearHandlers();
    restClient.AddHandler("*", new JsonDeserializer());
    if (!path.StartsWith("/")) path = "/" + path;

    restClient.Authenticator = new OAuthAuthenticator(restClient.BaseUrl, _apiKey, _appsecret, _userLogin.Token, _userLogin.Secret);

    var request = new RestRequest(Method.GET);
    request.Resource = "{version}/files/dropbox{path}";
    request.AddParameter("version", _version, ParameterType.UrlSegment);
    request.AddParameter("path", path, ParameterType.UrlSegment);

    var responseData = restClient.DownloadData(request);

    return responseData;
}

Note: This is assuming the user has already logged in and we have the token/secret (_userLogin).

Starting from the top, we create a new Instance of the RestSharp Client with the baseUrl then set the Json Deserializer for all requests. We then set the RestClient’s Authenticator to the OAuthAuthenticator and give it our baseUrl, all our secrets and that is all we need to do for OAuth (the rest is build into RestSharp, awesome?!). Now we create the Request up, its a GET method, set the version and path of the file to download call Execute and you have just downloaded your first Dropbox API file! I then converted this to a stream so save back to a local file.

Delete File:

public bool DeleteFile(string path)
{
    var restClient = new RestClient("http://api.dropbox.com");
    //load the JsonDeserializer for all types
    restClient.ClearHandlers();
    restClient.AddHandler("*", new JsonDeserializer());

    if (!path.StartsWith("/")) path = "/" + path;

    restClient.Authenticator = new OAuthAuthenticator(_restClient.BaseUrl, _apiKey, _appsecret, _userLogin.Token, _userLogin.Secret);

    var request = new RestRequest(Method.GET);
    request.Resource = "{version}/fileops/delete";
    request.AddParameter("version", _version, ParameterType.UrlSegment);

    request.AddParameter("path", path);
    request.AddParameter("root", "dropbox");

    var response = restClient.Execute(request);

    return response.StatusCode == System.Net.HttpStatusCode.OK;
}

Delete is pretty similar to Download, only differences is the Url, the response and this time the path is sent as a parameter instead of part of the Url. The “root” parameter is for applications that only have sandbox access (they would set this to sandbox) who only get access to a “sandbox” folder on the users dropbox account.

Upload File:

Now this is where I had the most difficulties, many “Forbidden” messages later I finally came up with the solution!

public bool UploadFile(string path, FileInfo localFile)
{
    var restClient = new RestClient("http://api-content.dropbox.com");
    //load the JsonDeserializer for all types
    restClient.ClearHandlers();
    restClient.AddHandler("*", new JsonDeserializer());

    if (!path.StartsWith("/")) path = "/" + path;

    //Get the file stream
    byte[] bytes = null;
    FileStream fs = new FileStream(localFile.FullName, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = localFile.Length;
    bytes = br.ReadBytes((int)numBytes);

    restClient.Authenticator = new OAuthAuthenticator(_restClient.BaseUrl, _apiKey, _appsecret, _userLogin.Token, _userLogin.Secret);

    var request = new RestRequest(Method.POST);
    request.Resource = "{version}/files/dropbox{path}";
    request.AddParameter("version", _version, ParameterType.UrlSegment);
    request.AddParameter("path", path, ParameterType.UrlSegment);
    //Need to add the "file" parameter with the file name
    request.AddParameter("file", localFile.Name);

    request.AddFile(new FileParameter { Data = bytes, FileName = localFile.Name, ParameterName = "file" });

    var response = restClient.Execute(request);

    return response.StatusCode == System.Net.HttpStatusCode.OK;
}

Ok to start with the “path” variable/parameter is the folder path (not the file).

Starts off the same with the RestClient, JsonDeserializer and the OAuthAuthenticator. We also need to read the file as a byte array. Now this request is a POST so we set that in the RestRequest object then add the version and path Url parameters. We also need to add the Filename as a “file” parameter for this request as well as adding the actual file to the Request. Execute that and: {\"result\": \"winner!\"} we just uploaded a file to dropbox!

This code was taken from my Dropbox open source .NET project called DropNet.