Dropbox.NET

Dropbox API is a .NET SDK for API v2, which helps you easily integrate Dropbox into your app. The Dropbox .NET SDK is a Portable Class Library that works with multiple platforms, including Windows, Windows Phone, and Mono.

Step 1 Create a WPF Application

  • Create a new WPF application.

    WPF application

Step 2 Install Dropbox.NET SDK in to the project

  • Dropbox.NET SDK can be installed through NuGet.
  • Open NuGet Package Manager Console (PMC) in Visual Studio.

    NuGet Package Manager

  • Run the below-mentioned command in PMC to install Dropbox API.

    PM> Install-Package Dropbox.Api
  • Follow the basic steps to complete the installation.
  • After successful installation, Dropbox.Api will be added into the project references.

    Dropbox.Api

Step 3 Create App in Dropbox

  • Go to the below-mentioned link to create an account in Dropbox.
    https://www.dropbox.com
  • Navigate to below-mentioned link to create new app required to work with Dropbox API.
    https://www.dropbox.com/developers/apps
  • Follow the steps and create a new app as per your convenience.

Step 4 Configure Created App for Access

  • Click on the created application and redirect to the Settings tab.

    WPF

  • Initially, only one user can access API and to enable multiple users, click on “Enable additional users” button. This will allow 500 users to use this app for API use.
  • App Key: This is a unique key generated for this app which will be required for the API connection.
  • Redirected URIs: Here, we can add redirection URIs required for the API connection. (For testing purpose, we should add https://localhost.authorize)
  • There is no fixed pattern for the URL, We can go with the structure as per our convenience.

Step 5 Start Development for API Integration.

  • In the above 4 steps, we have completed the prerequisite steps required to start development related to API Integration.
  • Same as Prerequisite, we have to do some authentication steps to login into Dropbox for Upload, Download etc. operations.

DropBoxBase Class

  • This class contains all the operations related to Dropbox.
    1. using Dropbox.Api;
    2. using Dropbox.Api.Files;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.IO;
    6. using System.Linq;
    7. using System.Net.Http;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using System.Windows;
    11. namespace DropBoxIntegration
    12. {
    13. class DropBoxBase
    14. {
    15. #region Variables
    16. private DropboxClient DBClient;
    17. private ListFolderArg DBFolders;
    18. private string oauth2State;
    19. private const string RedirectUri = "https://localhost/authorize"; // Same as we have configured Under [Application] -> settings -> redirect URIs.
    20. #endregion
    21. #region Constructor
    22. public DropBoxBase(string ApiKey, string ApiSecret, string ApplicationName = "TestApp")
    23. {
    24. try
    25. {
    26. AppKey = ApiKey;
    27. AppSecret = ApiSecret;
    28. AppName = ApplicationName;
    29. }
    30. catch (Exception)
    31. {
    32. throw;
    33. }
    34. }
    35. #endregion
    36. #region Properties
    37. public string AppName
    38. {
    39. get; private set;
    40. }
    41. public string AuthenticationURL
    42. {
    43. get; private set;
    44. }
    45. public string AppKey
    46. {
    47. get; private set;
    48. }
    49. public string AppSecret
    50. {
    51. get; private set;
    52. }
    53. public string AccessTocken
    54. {
    55. get; private set;
    56. }
    57. public string Uid
    58. {
    59. get; private set;
    60. }
    61. #endregion
    62. #region UserDefined Methods
    63. /// <summary>
    64. /// This method is to generate Authentication URL to redirect user for login process in Dropbox.
    65. /// </summary>
    66. /// <returns></returns>
    67. public string GeneratedAuthenticationURL()
    68. {
    69. try
    70. {
    71. this.oauth2State = Guid.NewGuid().ToString("N");
    72. Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, AppKey, RedirectUri, state: oauth2State);
    73. AuthenticationURL = authorizeUri.AbsoluteUri.ToString();
    74. return authorizeUri.AbsoluteUri.ToString();
    75. }
    76. catch (Exception)
    77. {
    78. throw;
    79. }
    80. }
    81. /// <summary>
    82. /// This method is to generate Access Token required to access dropbox outside of the environment (in ANy application).
    83. /// </summary>
    84. /// <returns></returns>
    85. public string GenerateAccessToken()
    86. {
    87. try
    88. {
    89. string _strAccessToken = string.Empty;
    90. if (CanAuthenticate())
    91. {
    92. if (string.IsNullOrEmpty(AuthenticationURL))
    93. {
    94. throw new Exception("AuthenticationURL is not generated !");
    95. }
    96. Login login = new Login(AppKey, AuthenticationURL, this.oauth2State); // WPF window with Webbrowser control to redirect user for Dropbox login process.
    97. login.Owner = Application.Current.MainWindow;
    98. login.ShowDialog();
    99. if (login.Result)
    100. {
    101. _strAccessToken = login.AccessToken;
    102. AccessTocken = login.AccessToken;
    103. Uid = login.Uid;
    104. DropboxClientConfig CC = new DropboxClientConfig(AppName, 1);
    105. HttpClient HTC = new HttpClient();
    106. HTC.Timeout = TimeSpan.FromMinutes(10); // set timeout for each ghttp request to Dropbox API.
    107. CC.HttpClient = HTC;
    108. DBClient = new DropboxClient(AccessTocken, CC);
    109. }
    110. else
    111. {
    112. DBClient = null;
    113. AccessTocken = string.Empty;
    114. Uid = string.Empty;
    115. }
    116. }
    117. return _strAccessToken;
    118. }
    119. catch (Exception ex)
    120. {
    121. throw ex;
    122. }
    123. }
    124. /// <summary>
    125. /// Method to create new folder on Dropbox
    126. /// </summary>
    127. /// <param name="path"> path of the folder we want to create on Dropbox</param>
    128. /// <returns></returns>
    129. public bool CreateFolder(string path)
    130. {
    131. try
    132. {
    133. if (AccessTocken == null)
    134. {
    135. throw new Exception("AccessToken not generated !");
    136. }
    137. if (AuthenticationURL == null)
    138. {
    139. throw new Exception("AuthenticationURI not generated !");
    140. }
    141. var folderArg = new CreateFolderArg(path);
    142. var folder = DBClient.Files.CreateFolderAsync(folderArg);
    143. var result = folder.Result;
    144. return true;
    145. }
    146. catch (Exception ex)
    147. {
    148. return false;
    149. }
    150. }
    151. /// <summary>
    152. /// Method is to check that whether folder exists on Dropbox or not.
    153. /// </summary>
    154. /// <param name="path"> Path of the folder we want to check for existance.</param>
    155. /// <returns></returns>
    156. public bool FolderExists(string path)
    157. {
    158. try
    159. {
    160. if (AccessTocken == null)
    161. {
    162. throw new Exception("AccessToken not generated !");
    163. }
    164. if (AuthenticationURL == null)
    165. {
    166. throw new Exception("AuthenticationURI not generated !");
    167. }
    168. var folders = DBClient.Files.ListFolderAsync(path);
    169. var result = folders.Result;
    170. return true;
    171. }
    172. catch (Exception ex)
    173. {
    174. return false;
    175. }
    176. }
    177. /// <summary>
    178. /// Method to delete file/folder from Dropbox
    179. /// </summary>
    180. /// <param name="path">path of file.folder to delete</param>
    181. /// <returns></returns>
    182. public bool Delete(string path)
    183. {
    184. try
    185. {
    186. if (AccessTocken == null)
    187. {
    188. throw new Exception("AccessToken not generated !");
    189. }
    190. if (AuthenticationURL == null)
    191. {
    192. throw new Exception("AuthenticationURI not generated !");
    193. }
    194. var folders = DBClient.Files.DeleteAsync(path);
    195. var result = folders.Result;
    196. return true;
    197. }
    198. catch (Exception ex)
    199. {
    200. return false;
    201. }
    202. }
    203. /// <summary>
    204. /// Method to upload files on Dropbox
    205. /// </summary>
    206. /// <param name="UploadfolderPath"> Dropbox path where we want to upload files</param>
    207. /// <param name="UploadfileName"> File name to be created in Dropbox</param>
    208. /// <param name="SourceFilePath"> Local file path which we want to upload</param>
    209. /// <returns></returns>
    210. public bool Upload(string UploadfolderPath, string UploadfileName, string SourceFilePath)
    211. {
    212. try
    213. {
    214. using (var stream = new MemoryStream(File.ReadAllBytes(SourceFilePath)))
    215. {
    216. var response = DBClient.Files.UploadAsync(UploadfolderPath + "/" + UploadfileName, WriteMode.Overwrite.Instance, body: stream);
    217. var rest = response.Result; //Added to wait for the result from Async method
    218. }
    219. return true;
    220. }
    221. catch (Exception ex)
    222. {
    223. return false;
    224. }
    225. }
    226. /// <summary>
    227. /// Method to Download files from Dropbox
    228. /// </summary>
    229. /// <param name="DropboxFolderPath">Dropbox folder path which we want to download</param>
    230. /// <param name="DropboxFileName"> Dropbox File name availalbe in DropboxFolderPath to download</param>
    231. /// <param name="DownloadFolderPath"> Local folder path where we want to download file</param>
    232. /// <param name="DownloadFileName">File name to download Dropbox files in local drive</param>
    233. /// <returns></returns>
    234. public bool Download(string DropboxFolderPath, string DropboxFileName, string DownloadFolderPath, string DownloadFileName)
    235. {
    236. try
    237. {
    238. var response = DBClient.Files.DownloadAsync(DropboxFolderPath + "/" + DropboxFileName);
    239. var result = response.Result.GetContentAsStreamAsync(); //Added to wait for the result from Async method
    240. return true;
    241. }
    242. catch (Exception ex)
    243. {
    244. return false;
    245. }
    246. }
    247. #endregion
    248. #region Validation Methods
    249. /// <summary>
    250. /// Validation method to verify that AppKey and AppSecret is not blank.
    251. /// Mendatory to complete Authentication process successfully.
    252. /// </summary>
    253. /// <returns></returns>
    254. public bool CanAuthenticate()
    255. {
    256. try
    257. {
    258. if (AppKey == null)
    259. {
    260. throw new ArgumentNullException("AppKey");
    261. }
    262. if (AppSecret == null)
    263. {
    264. throw new ArgumentNullException("AppSecret");
    265. }
    266. return true;
    267. }
    268. catch (Exception)
    269. {
    270. throw;
    271. }
    272. }
    273. #endregion
    274. }
    275. }

Login Window

  • Form to redirect the user for login into Dropbox for authentication.

XAML

  1. <Window x:Class="DropBoxIntegration.Login"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:DropBoxIntegration"
  7. mc:Ignorable="d" WindowStartupLocation="CenterOwner" WindowStyle="ToolWindow"
  8. Title="Login" BorderThickness="2" BorderBrush="#FF333738" Loaded="Window_Loaded">
  9. <Grid>
  10. <Grid.ColumnDefinitions>
  11. <ColumnDefinition Width="457*"/>
  12. <ColumnDefinition Width="30"/>
  13. </Grid.ColumnDefinitions>
  14. <Grid.RowDefinitions>
  15. <RowDefinition Height="30"/>
  16. <RowDefinition Height="131*"/>
  17. </Grid.RowDefinitions>
  18. <Border HorizontalAlignment="Stretch"
  19. VerticalAlignment="Stretch" Margin="2" Grid.Row="1" Grid.ColumnSpan="2" SnapsToDevicePixels="True">
  20. <WebBrowser x:Name="Browser" Navigating="Browser_Navigating"/>
  21. </Border>
  22. </Grid>
  23. </Window>

.CS Class

  1. using Dropbox.Api;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Shapes;
  15. namespace DropBoxIntegration
  16. {
  17. /// <summary>
  18. /// Interaction logic for Login.xaml
  19. /// </summary>
  20. public partial class Login : Window
  21. {
  22. #region Variables
  23. private const string RedirectUri = "https://localhost/authorize";
  24. private string DBAppKey = string.Empty;
  25. private string DBAuthenticationURL = string.Empty;
  26. private string DBoauth2State = string.Empty;
  27. #endregion
  28. #region Properties
  29. public string AccessToken { get; private set; }
  30. public string UserId { get; private set; }
  31. public bool Result { get; private set; }
  32. #endregion
  33. public Login(string AppKey, string AuthenticationURL, string oauth2State)
  34. {
  35. InitializeComponent();
  36. DBAppKey = AppKey;
  37. DBAuthenticationURL = AuthenticationURL;
  38. DBoauth2State = oauth2State;
  39. }
  40. public void Navigate()
  41. {
  42. try
  43. {
  44. if (!string.IsNullOrEmpty(DBAppKey))
  45. {
  46. Uri authorizeUri = new Uri(DBAuthenticationURL);
  47. Browser.Navigate(authorizeUri);
  48. }
  49. }
  50. catch (Exception)
  51. {
  52. throw;
  53. }
  54. }
  55. private void Window_Loaded(object sender, RoutedEventArgs e)
  56. {
  57. Dispatcher.BeginInvoke(new Action(Navigate));
  58. // Navigate();
  59. }
  60. private void Button_Click(object sender, RoutedEventArgs e)
  61. {
  62. try
  63. {
  64. this.Close();
  65. }
  66. catch (Exception)
  67. {
  68. throw;
  69. }
  70. }
  71. private void Browser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
  72. {
  73. if (!e.Uri.AbsoluteUri.ToString().StartsWith(RedirectUri.ToString(), StringComparison.OrdinalIgnoreCase))
  74. {
  75. // we need to ignore all navigation that isn't to the redirect uri.
  76. return;
  77. }
  78. try
  79. {
  80. OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
  81. if (result.State != DBoauth2State)
  82. {
  83. return;
  84. }
  85. this.AccessToken = result.AccessToken;
  86. this.Uid = result.Uid;
  87. this.Result = true;
  88. }
  89. catch (ArgumentException ex)
  90. {
  91. }
  92. finally
  93. {
  94. e.Cancel = true;
  95. this.Close();
  96. }
  97. }
  98. }
  99. }

MainWindow

  • UI Interface to work with Dropbox.

Xaml

  1. <Window x:Class="DropBoxIntegration.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:DropBoxIntegration"
  7. mc:Ignorable="d"
  8. Title="MainWindow" Height="321" Width="1024" MinHeight="300" MinWidth="600">
  9. <Grid>
  10. <Grid.RowDefinitions>
  11. <RowDefinition Height="35"/>
  12. <RowDefinition Height="70"/>
  13. <RowDefinition Height="113*"/>
  14. <RowDefinition Height="20"/>
  15. </Grid.RowDefinitions>
  16. <Label Content="Work with your DropBox account" FontSize="18" Foreground="Black" FontWeight="SemiBold" Margin="20,0,5,0"></Label>
  17. <GroupBox x:Name="gbAuthentication" HorizontalAlignment="Stretch" Margin="2" VerticalAlignment="Stretch" Grid.Row="1" Background="White">
  18. <GroupBox.Header>
  19. <Label Content="DropBox Authentication" FontWeight="SemiBold"></Label>
  20. </GroupBox.Header>
  21. <Grid>
  22. <Grid.ColumnDefinitions>
  23. <ColumnDefinition Width="100"/>
  24. <ColumnDefinition Width="100*"/>
  25. <ColumnDefinition Width="100"/>
  26. </Grid.ColumnDefinitions>
  27. <Label Content="App Key: " Grid.Column="0" HorizontalContentAlignment="Right" Margin="2"/>
  28. <TextBox x:Name="txtApiKey" Grid.Column="1" Margin="2" MaxLength="100" Text=""></TextBox>
  29. <Button Content="Authenticate" x:Name="btnApiKey" Grid.Column="2" Margin="2" Click="btnApiKey_Click"></Button>
  30. </Grid>
  31. </GroupBox>
  32. <GroupBox x:Name="gbDropBox" HorizontalAlignment="Stretch" Margin="2" Grid.Row="2" VerticalAlignment="Stretch" Background="White" IsEnabled="false">
  33. <GroupBox.Header>
  34. <Label Content="DropBox Operations" FontWeight="SemiBold"></Label>
  35. </GroupBox.Header>
  36. <Grid>
  37. <Grid.ColumnDefinitions>
  38. <ColumnDefinition Width="05"/>
  39. <ColumnDefinition Width="220*"/>
  40. <ColumnDefinition Width="220*"/>
  41. <ColumnDefinition Width="220*"/>
  42. <ColumnDefinition Width="220*"/>
  43. <ColumnDefinition Width="05"/>
  44. </Grid.ColumnDefinitions>
  45. <Grid.RowDefinitions>
  46. <RowDefinition Height="05"/>
  47. <RowDefinition Height="150*"/>
  48. <RowDefinition Height="05"/>
  49. </Grid.RowDefinitions>
  50. <Button x:Name="btnCreateFolder" Content="Create Folder" HorizontalAlignment="Stretch" Margin="5" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="1" FontSize="14" Click="btnCreateFolder_Click"/>
  51. <Button x:Name="btlUpload" Content="Upload File" HorizontalAlignment="Stretch" Margin="5" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="2" FontSize="14" Click="btlUpload_Click"/>
  52. <Button x:Name="btnDownload" Content="Download File" HorizontalAlignment="Stretch" Margin="5" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="3" FontSize="14" Click="btnDownload_Click"/>
  53. <Button x:Name="btnDelete" Content="Delete File/Directory" HorizontalAlignment="Stretch" Margin="5" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="4" FontSize="14" Click="btnDelete_Click"/>
  54. </Grid>
  55. </GroupBox>
  56. </Grid>
  57. </Window>

.CS File

  1. using Dropbox.Api;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Navigation;
  15. using System.Windows.Shapes;
  16. namespace DropBoxIntegration
  17. {
  18. /// <summary>
  19. /// Interaction logic for MainWindow.xaml
  20. /// </summary>
  21. public partial class MainWindow : Window
  22. {
  23. #region Variables
  24. private string strAppKey = "[Yor Application App Key]";
  25. private string strAccessToken = string.Empty;
  26. private string strAuthenticationURL = string.Empty;
  27. private DropBoxBase DBB;
  28. #endregion
  29. #region Constructor
  30. public MainWindow()
  31. {
  32. InitializeComponent();
  33. }
  34. #endregion
  35. #region Private Methods
  36. public void Authenticate()
  37. {
  38. try
  39. {
  40. if (string.IsNullOrEmpty(strAppKey))
  41. {
  42. MessageBox.Show("Please enter valid App Key !");
  43. return;
  44. }
  45. if (DBB == null)
  46. {
  47. DBB = new DropBoxBase(strAppKey, "TestApp");
  48. strAuthenticationURL = DBB.GeneratedAuthenticationURL(); // This method must be executed before generating Access Token.
  49. strAccessToken = DBB.GenerateAccessToken();
  50. gbDropBox.IsEnabled = true;
  51. }
  52. else gbDropBox.IsEnabled = false;
  53. }
  54. catch (Exception)
  55. {
  56. throw;
  57. }
  58. }
  59. #endregion
  60. private void btnApiKey_Click(object sender, RoutedEventArgs e)
  61. {
  62. try
  63. {
  64. strAppKey = txtApiKey.Text.Trim();
  65. Authenticate();
  66. }
  67. catch (Exception)
  68. {
  69. throw;
  70. }
  71. }
  72. private void btnCreateFolder_Click(object sender, RoutedEventArgs e)
  73. {
  74. try
  75. {
  76. if (DBB != null)
  77. {
  78. if (strAccessToken != null && strAuthenticationURL != null)
  79. {
  80. if (DBB.FolderExists("/Dropbox/DotNetApi") == false)
  81. {
  82. DBB.CreateFolder("/Dropbox/DotNetApi");
  83. }
  84. }
  85. }
  86. }
  87. catch (Exception ex)
  88. {
  89. ex = ex.InnerException ?? ex;
  90. }
  91. }
  92. private void btlUpload_Click(object sender, RoutedEventArgs e)
  93. {
  94. try
  95. {
  96. if (DBB != null)
  97. {
  98. if (strAccessToken != null && strAuthenticationURL != null)
  99. {
  100. DBB.Upload("/Dropbox/DotNetApi", "Sample-test.jpg", @"D:\Capture4-test.PNG");
  101. }
  102. }
  103. }
  104. catch (Exception)
  105. {
  106. throw;
  107. }
  108. }
  109. private void btnDownload_Click(object sender, RoutedEventArgs e)
  110. {
  111. try
  112. {
  113. if (DBB != null)
  114. {
  115. if (strAccessToken != null && strAuthenticationURL != null)
  116. {
  117. DBB.Download("/Dropbox/DotNetApi", "Sample-test.jpg", @"D:\", "capture4_dwnld.png");
  118. }
  119. }
  120. }
  121. catch (Exception)
  122. {
  123. throw;
  124. }
  125. }
  126. private void btnDelete_Click(object sender, RoutedEventArgs e)
  127. {
  128. try
  129. {
  130. if (DBB != null)
  131. {
  132. if (strAccessToken != null && strAuthenticationURL != null)
  133. {
  134. DBB.Delete("/Dropbox/DotNetApi");
  135. }
  136. }
  137. }
  138. catch (Exception)
  139. {
  140. throw;
  141. }
  142. }
  143. }
  144. }
That’s it. We are done with the integration. Enjoy Coding!