Easy Steps to Access Files in Dropbox and Use Them in a Xamarin App
Tags: csharp, android, ios, dropbox
Published: 2020-06-19 07:24:34

---
title: Easy Steps to Access Files in Dropbox and Use Them in a Xamarin App
published: true
date: 2020-06-17 11:40:24 UTC
tags: csharp, android, ios, dropbox
canonical_url: https://www.syncfusion.com/blogs/post/access-files-in-dropbox-and-use-them-in-xamarin-app.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/596-334.png
---

We all know that [Dropbox](https://en.wikipedia.org/wiki/Dropbox_(service)) is one of the most popular file-hosting services for the cloud. However, at some point, we all have found it hard to access files available in the Dropbox and use them in our Xamarin applications.

In this blog, we will walk you through the steps to access files in Dropbox and use them in a Xamarin.Forms application, with an example of accessing a PDF file and displaying it in our [Syncfusion Xamarin PDF Viewer](https://www.syncfusion.com/xamarin-ui-controls/xamarin-pdf-viewer).

Let’s get started!

## Register your application in Dropbox

**Step 1:** To start with, you need to register your application in the Dropbox platform. For that, navigate to the Dropbox [developers site](https://www.dropbox.com/developers) and click Create Apps.

**Step 2:** Next, select the type of API you want to use with your application. The suggested option is to use the free **Dropbox API**.

**![Choose-Dropbox-API](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/Choose-Dropbox-API-1.png)Step 3:** Then, select the access mode. You can restrict the access to the application to a specific folder or allow access to all the folders.  
 ![Choose-the-type-of-access-you-need](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/Choose-the-type-of-access-you-need-1.png)

**Step 4:** Finally, provide a name for your application and click **Create app**.  
 ![Name-your-app](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/Name-your-app-1.png)

**Step 5:** Then, the following page will be displayed with the application settings information in it. You need to use this **App secret** key information to generate an **OAuth2 access token**.  
 ![App-secret-key-to-generate-OAuth2-access-token](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/App-secret-key-to-generate-OAuth2-access-token-1.png)

For a simple C# console application, you can directly generate the access tokens from the developer site and use them in your program. So, you should copy this token and use it in the client application to establish the connection.

Use the Dropbox API class **DropboxClient** to establish the connection and manage the files. For more details, please refer to this [tutorial](https://www.dropbox.com/developers/documentation/dotnet#tutorial).

But in our Xamarin application, we are going to generate the access token programmatically to manage the Dropbox files.

## Access Dropbox files and use them in a Xamarin application

Please follow these steps to establish the connection, access PDF files in the Dropbox, and view them using our Syncfusion Xamarin PDF Viewer.

**Step 1:** Create a new Xamarin.Forms project.

**Step 2:** Install the packages **Dropbox.Api** in the PCL project and **Syncfusion.Xamarin.SfPdfViewer** in all the projects.  
 ![Choose-Dropbox.Api_](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/Choose-Dropbox.Api_-1.png)

**Step 3:** Create a ViewModel class and name it **DropboxViewModel.** Add a binding property **PdfDocumentStream** of type **Stream** in the ViewModel class. Then, in the MainPage.xaml, set the binding context as **DropboxViewModel** and add the **SfPdfViewer** control. Then bind the **InputFileStream** property of SfPdfViewer to the **PdfDocumentStream** property.

**Step 4:** Create a class named **DropboxService** and add all the logic to establish the connection and obtain the information from the Dropbox. Here, we use **Webview** to display the login interface. In its navigation event, add the logic to obtain the Dropbox access token once when the authentication is completed. The **ClientId** (App secret) and **RedirectUri** values can be obtained from the Dropbox developers site/console.

Please take a look at the code example.

```csharp
private const string ClientId = "Your App secret key";
 
private const string RedirectUri = "Your Redirect Uri";
 
/// <summary>
///     <para>Runs the Dropbox OAuth authorization process if not yet authenticated.</para>
///     <para>Upon completion <seealso cref="OnAuthenticated"/> is called</para>
/// </summary>
/// <returns>An asynchronous task.</returns>
public async Task Authorize()
{
    Application.Current.Properties.Clear();
 
    if (string.IsNullOrWhiteSpace(this.AccessToken) == false)
    {
        // Already authorized
        this.OnAuthenticated?.Invoke();
        return;
    }
 
    // Run Dropbox authentication
    this.oauth2State = Guid.NewGuid().ToString("N");
    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ClientId, new Uri(RedirectUri), this.oauth2State);
    var webView = new WebView { Source = new UrlWebViewSource { Url = authorizeUri.AbsoluteUri } };
    webView.Navigating += this.WebViewOnNavigating;
    var contentPage = new ContentPage { Content = webView };
    await Application.Current.MainPage.Navigation.PushModalAsync(contentPage);
}
```

**Step 5:** Once the user has logged into Dropbox, the URL for the Webview will contain the access token to authenticate all other requests. Please find the code example of the Webview navigation event in the following.

```csharp
private async void WebViewOnNavigating(object sender, WebNavigatingEventArgs e)
{
    if (!e.Url.StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
    {
        // we need to ignore all navigation that isn't to the redirect uri.
        return;
    }
    try
    {
        var result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(e.Url));
        if (result.State != this.oauth2State)
        {
            return;
        }
        this.AccessToken = result.AccessToken;
        this.OnAuthenticated?.Invoke();
    }
    catch (ArgumentException)
    {
        // There was an error in the URI passed
    }
    finally
    {
        e.Cancel = true;
        await Application.Current.MainPage.Navigation.PopModalAsync();
    }
}     
```

**Step 6:** Now we have obtained the token and with the help of that, we can perform actions like getting the list of files; reading, writing, and saving files.

Please take a look at the code example.

```csharp
/// <summary>
/// Gets the Dropbox file list
/// </summary>
/// <returns>An asynchronous task</returns>
public async Task<IList<Metadata>> ListFiles()
{
    try
    {
        using (var client = this.GetClient())
        {
            var list = await client.Files.ListFolderAsync(string.Empty, true);
            return list?.Entries;
        }
    }
    catch (Exception)
    {                
        return null;
    }
}
 
/// <summary>
/// Reads the file from Dropbox and returns it as byte array
/// </summary>
/// <returns>An asynchronous task</returns>
public async Task<byte[]> ReadFile(string filePath)
{
    try
    {
        using (var client = this.GetClient())
        {
            var response = await client.Files.DownloadAsync(filePath);
            var bytes = response?.GetContentAsByteArrayAsync();
            return bytes?.Result;
        }
    }
    catch (Exception)
    {                
        return null;
    }
}
 
/// <summary>
/// Writes the file to the Dropbox
/// </summary>
/// <returns>An asynchronous task</returns>
public async Task<FileMetadata> WriteFile(MemoryStream fileContent, string fileName)
{
    try
    {
        var commitInfo = new CommitInfo(fileName, WriteMode.Overwrite.Instance, false, DateTime.Now);
 
        using (var client = this.GetClient())
        {
            var metadata = await client.Files.UploadAsync(commitInfo, fileContent);
            return metadata;
        }
    }
    catch (Exception)
    {                
        return null;
    }
}
```

**Step 7:** To view the PDF file in Dropbox in our Syncfusion Xamarin PDF Viewer, call the **ReadFile(_string fileName_)** method and convert the resultant byte array to stream. Then, assign the converted stream to the **PdfDocumentStream** property in the **DropboxViewModel** class.

**Step 8:** Similarly, you can call the **WriteFile(_MemoryStream fileContent, string fileName_)** method to write or save the modified PDF back in the Dropbox.

## Dropbox sample project

You can find the sample project of loading and saving Dropbox PDF files using Syncfusion Xamarin PDF Viewer in this [GitHub](https://github.com/SyncfusionExamples/Access-pdf-files-from-dropbox-and-load-them-using-xamarin-pdf-viewer) location. The following steps describe the procedures involved in working with this sample project.

**Step 1:** In this sample, initially a Dropbox login interface will be displayed for your Dropbox credentials.
![drop box in Xamarin](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/drop-box.jpg)  
**Step 2:** After entering your credentials, the list of PDF files from the user’s Dropbox account will be displayed in a pop-up list view. You can select any PDF file from the list to view it in the PDF Viewer control. You can also select another file by clicking on the** Files** option in the top grid section.  
 ![choose your desired file](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/choose-your-desired-file.jpg)

**Step 3:** Then, you can edit the PDF file loaded using the options in the PDF Viewer control. Also, you can save them to the signed-in Dropbox account by clicking on the save option.

**Step 4:** Once Save is clicked, a pop-up view to obtain the file name will be displayed. Entering a file name (e.g., PDF\_Succinctly.pdf) and clicking **OK** will save the document in the Dropbox.

**Step 5:** You could also save the file to a specific folder by providing the file name in this format: **folder name/file name** (e.g., Syncfusion/PDF\_Succinctly2.pdf).  
 ![choose save option](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/choose-save-option@1x.jpg)

## ![enter the file name](https://www.syncfusion.com/blogs/wp-content/uploads/2020/06/enter-the-file-name@1x.jpg)  
Conclusion

I hope you now have a clear idea about how to access files from Dropbox and use them in a Xamarin application. You can also perform various other operations as described in the [Dropbox tutorial documentation](https://www.dropbox.com/developers/documentation/dotnet#tutorial). I leave them for you to experiment with. Try them and share your feedback in the comments section below.

If you aren’t a customer yet, you can try our 30-day [free trial](https://www.syncfusion.com/downloads) to check out these features. Also, try our other samples from this [GitHub](https://github.com/syncfusion/wpf-demos/tree/master/PDF%20Viewer) location.

If you wish to send us feedback or would like to submit any questions, please feel free to contact us through our [support forum](https://www.syncfusion.com/forums), [Direct-Trac,](https://www.syncfusion.com/support/directtrac/) or [feedback portal](https://www.syncfusion.com/feedback/). We are always happy to assist you!

If you like this post, we think you will also enjoy the following eBook and other articles as well:

- [eBook] [PDF Succinctly](https://www.syncfusion.com/ebooks/pdf)
- [Blog] [Why Waste Memory Saving Annotated PDFs When You Can Export Them Using the Xamarin PDF Viewer?](https://dev.to/karthickramasamy08/why-waste-memory-saving-annotated-pdfs-when-you-can-export-them-using-the-xamarin-pdf-viewer-o1c-temp-slug-9838386)
- [Blog] [Adding a Custom Stamp to a PDF Using Xamarin PDF Viewer](https://dev.to/syncfusion/adding-a-custom-stamp-to-a-pdf-using-xamarin-pdf-viewer-2hg)
- [Blog] [Digitally Sign and Verify signature in PDF File Using C#: A Complete Guide](https://www.syncfusion.com/blogs/post/create-validate-pdf-digital-signatures-csharp.aspx)

The post [Easy Steps to Access Files in Dropbox and Use Them in a Xamarin App](https://www.syncfusion.com/blogs/post/access-files-in-dropbox-and-use-them-in-xamarin-app.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).