Integrating Dropbox file upload into Desktop application
In this fifth installment of our GSMArena Scraper series, we’ll cover how to prepare your Dropbox account for file uploads and walk through the C# techniques we used to integrate Dropbox file upload functionality into our WinForms application. We’ll also break down our custom DropboxUploader.cs class to understand how it works under the hood.
1. Preparing Dropbox to Receive File Uploads
Before your WinForms application can upload files to Dropbox, you’ll need to set up your Dropbox app and obtain the necessary credentials.
- Go to the Dropbox Developers Console.
- Sign in and click Create App.
- Select Scoped Access and choose the permission type Full Dropbox or App Folder.
- Give your app a unique name and click Create App.
- Navigate to the Permissions tab and enable files.content.write and files.content.read.
- Generate an Access Token under the OAuth 2 section.
Below are some example screenshots showing these steps:
2. Uploading Files to Dropbox from a C# WinForms Project
We implemented Dropbox file upload functionality in our Visual Studio 2022 project targeting .NET 9.0. Below is the high-level workflow:
- Read file path from local storage.
- Use the Dropbox API endpoint
/2/files/upload
. - Pass the access token in the HTTP header.
- Send the file data as a binary stream in the request body.
- Handle the response to confirm upload success or capture any errors.
Here’s an example C# method to upload a file (simplified version):
// Simplified Dropbox Upload Example
public async Task UploadToDropbox(string localFilePath, string dropboxAccessToken)
{
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", dropboxAccessToken);
httpClient.DefaultRequestHeaders.Add("Dropbox-API-Arg",
JsonConvert.SerializeObject(new { path = "/MyUploads/" + Path.GetFileName(localFilePath) }));
httpClient.DefaultRequestHeaders.Add("Content-Type", "application/octet-stream");
using var fileStream = File.OpenRead(localFilePath);
var response = await httpClient.PostAsync(
"https://content.dropboxapi.com/2/files/upload",
new StreamContent(fileStream));
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
3. Inside Our DropboxUploader.cs Class
Our DropboxUploader.cs class is designed to encapsulate the Dropbox upload logic, making it reusable and easy to maintain.
using Dropbox.Api;
using Dropbox.Api.Common;
using Dropbox.Api.Files;
using Dropbox.Api.Stone;
using Dropbox.Api.Team;
using Dropbox.Api.Users;
using System.Configuration;
using System.Diagnostics;
using System.Net;
namespace clsGsmar.CloudUpload
{
public class DropBoxUploader
{
//I am using a seprate json file in the UI Project to cover my credentials, you can
//add yours here while testing.
//private const string AppKey = "xxxxx"; // From Dropbox App Console
//private const string AppSecret = "xxxxx"; // From Dropbox App Console
//private const string RedirectUri = "http://localhost:XXXX/authorize"; // Must match your app settings
public string AccessToken { get; private set; } = string.Empty;
private DropboxClient dropboxClient;
public async Task AuthenticateAsync()
{
var creds = DropboxCredentials.Load();
string AppKey = creds.AppKey;
string AppSecret = creds.AppSecret;
string RedirectUri = creds.RedirectUri;
var state = Guid.NewGuid().ToString("N");
var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(
OAuthResponseType.Code,
AppKey,
new Uri(RedirectUri),
state: state);
using var listener = new HttpListener();
listener.Prefixes.Add(RedirectUri + "/");
listener.Start();
Process.Start(new ProcessStartInfo
{
FileName = authorizeUri.ToString(),
UseShellExecute = true
});
var context = await listener.GetContextAsync();
var response = context.Response;
var query = context.Request.QueryString;
var code = query["code"];
var receivedState = query["state"];
string responseHtml = "You can close this window.
";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseHtml);
response.ContentLength64 = buffer.Length;
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
response.Close();
listener.Stop();
if (string.IsNullOrEmpty(code) || receivedState != state)
return false;
var tokenResult = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
code,
AppKey,
AppSecret,RedirectUri,client: null,codeVerifier: null);
AccessToken = tokenResult.AccessToken;
dropboxClient = new DropboxClient(AccessToken);
return !string.IsNullOrEmpty(AccessToken);
}
public async Task UploadFileAsync(string localPath, string dropboxFileName = null)
{
if (dropboxClient == null)
throw new InvalidOperationException("Client not authenticated. Call AuthenticateAsync first.");
dropboxFileName ??= Path.GetFileName(localPath);
using (var fileStream = File.OpenRead(localPath))
{
var metadata = await dropboxClient.Files.UploadAsync(
"/" + dropboxFileName,
WriteMode.Overwrite.Instance,
body: fileStream
);
return metadata != null;
}
}
}
}
Key Features:
- Handles authentication with access token.
- Uploads files with proper API headers.
- Manages exceptions and retries for unstable connections.
- Supports custom Dropbox folder paths.
📺 Watch the Video Tutorial
For a step-by-step demonstration of the Dropbox integration, watch our video tutorial below:
Subscribe to our channel for more coding tutorials and project updates!
© 2025 GSMArena Scraper Project - All Rights Reserved.
🎯 Conclusion
By adding User-Agent and Proxy rotation with a smart fallback design, our GSMArena Web Data Scraper becomes a truly professional, user-friendly desktop application. This approach balances configurability, reliability, and ethical responsibility, making it perfect for researchers, bloggers, or hobbyist developers.
💬 Have questions about this project? Want to see the next part of the tutorial? Drop a comment below! And don't forget to check out my other .NET and WinForms guides.
♥ Here are some online Visual Basic lessons and courses:
No comments:
Post a Comment