Downloading and uploading files (Windows Runtime apps using C#/VB and XAML)

Allow users to download and upload files on Microsoft OneDrive, from your Windows Runtime app using C#/Visual Basic and XAML.

In this article
Prerequisites
Download a file
Upload a file
Update a file
Summary

Prerequisites

We assume that the user has already signed in and consented to the wl.skydrive scope for reading file or folder properties. If you have not added user sign-in to your Windows Runtime app, see Signing users in (XAML).

Download a file

To get the contents of a file, photo, video, or audio file, use code like you see in these steps. The wl.skydrive scope is required. You must ensure that the user has consented to the required scope; for details, see the first step under Upload a file.

  1. Download files. This example calls the LiveConnectClient.CreateBackgroundDownloadAsync(String, [IStorageFile]) method to create a download. The call to LiveDownloadOperation.StartAsync() method starts the download.

    try
    {
        LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync(filePath);
        var result = await operation.StartAsync();
        // Handle result.
    }
    catch
    {
        // Handle errors.
    }
    
  2. Handle pending downloads when the app restarts. When the app restarts, this example calls the LiveConnectClient.GetCurrentBackgroundDownloadsAsync method to get a list of files that are waiting to be downloaded. When the list has been populated, LiveUploadOperation.AttachAsync() method attaches and receives the result for each pending download. This step is necessary in case the app is terminated before the downloads are complete. If the app does not receive the result for a download, that download remains in the background service.

    var pendingOperations = await LiveConnectClient.GetCurrentBackgroundDownloadsAsync();
    foreach(LiveDownloadOperation pendingOperation in pendingOperations)
    {
        try
        {
         var opResult = await pendingOperation.AttachAsync();
         // Handle result.
        }
        catch
        {
           // Handle errors.
        }
    }
    

If your app is built for Windows Phone 8, call the LiveConnectClient.BackgroundDownloadAsync method to use the background transfer service. For details, see Transferring a file from a network resource and Windows.Networking.BackgroundTransfer.

private void btnDownloadFile_Begin(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
        return;
    }
    try
    {
        LiveConnectClient client = new LiveConnectClient(session);
        var downloadOperationResult = await client.DownloadAsync("file.a6b2a7e8f2515e5e.
            A6B2A7E8F2515E5E!131/picture?type=thumbnail");
        
        using (Stream downloadStream = downloadOperationResult.Stream)
        {
            if (downloadStream != null)
            {
                var imgSource = new BitmapImage();
                imgSource.SetSource(downloadStream);

                // imageFrame is a user-defined Image control.
                this.imageFrame.Source = imgSource;
                this.imageFrame.Visibility = Visibility.Visible;
            }
        }
    }
    catch (LiveConnectException ex)
    {
        infoTextBlock.Text = "Error downloading image: " + ex.Message;
    }
}

Upload a file

To upload a file, photo, video, or audio file, use code like what you see in these steps. You can upload file sizes up to 100 megabytes.

Note

Before uploading a file, have your app check that there is enough available OneDrive storage space by making a LiveConnectClient.GetAsync method call to USER_ID/skydrive/quota. For example, your app could get the size of the file, in bytes, and then compare it to the number of available storage bytes returned in the OneDrive quota call. For more info, see Get a user's total and remaining OneDrive storage quota.

  1. Make sure that the user has consented to the required scope, and then create an upload. The Upload method checks whether the user is signed in and has consented to the additional wl.skydrive_update scope before it invokes upload calls. This example calls the CreateBackgroundUploadAsync method with the destination folder, file name, stream, and OverwriteOption, to create an upload. The call to StartAsync starts the upload.

    private async void Upload()
    {
        try
        {
            // Ensure that the user has consented to the wl.skydrive and wl.skydrive_update scopes.
            var authClient = new LiveAuthClient();
            var authResult = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" });
            if (authResult.Session != null)
            {
                var liveConnectClient = new LiveConnectClient(authResult.Session);
    
                // Upload to OneDrive.
                LiveUploadOperation uploadOperation = await liveConnectClient.CreateBackgroundUploadAsync(
                    uploadPath, fileName, uploadInputStream, OverwriteOption.Rename);
                LiveOperationResult uploadResult = await uploadOperation.StartAsync();
                HandleUploadResult(uploadResult);
            }
        }
        catch (LiveAuthException ex)
        {
            // Handle errors.
        }
        catch(LiveConnectException ex)
        {
            // Handle errors.
        }
    }
    
    
  2. Handle pending uploads when the app restarts. This example invokes the LiveConnectClient.GetCurrentBackgroundUploadsAsync method to check for and receive pending uploads, and then calls the LiveUploadOperation.AttachAsync() method to receive the results. This step is necessary in case the app is terminated before the uploads are complete. If the app does not receive the result for an upload, that upload remains in the background service.

    Note

    The Microsoft.Live.LiveUploadOperation class has a Guid property that tracks pending operations. The Guid property is unique for each operation.

    var pendingOperations = await LiveConnectClient.GetCurrentBackgroundUploadsAsync();
    foreach(LiveDownloadOperation pendingOperation in pendingOperations)
    {
        try
        {
            var opResult = await pendingOperation.AttachAsync();
            // Handle results.
        }
        catch
        {
            // Handle errors.
        }
    }
    

If your app is built for Windows Phone 8, call the LiveConnectClient.BackgroundUploadAsync methods to use the background transfer service.

private async void Upload()
{
    ...
    try
    {
        LiveOperationResult uploadResult = await this.LiveConnectClient.BackgroundUploadAsync(
            uploadFolder,
            fileName,
            stream,
            OverwriteOption.Rename);
        HandleResult(uploadResult);
    }
    catch (LiveConnectException ex)
    {
        // Handle errors.
    }
 ...
}

Update a file

To change the contents of an existing file, photo, video, or audio, use the code in Upload a file but set the Microsoft.Live.OverwriteOption enumeration to Overwrite in the call to one of the LiveConnectClient.CreateBackgroundUploadAsync methods.

Summary

In this tutorial, you learned how to download and upload files to OneDrive. Next, we suggest you read Move, copy, create, or delete a file or folder to continue your learning.