Share via


Upload and Download files from OneDrive

 

Here is sample code to download and upload files to OneDrive  from Universal Windows Apps.

Complete source code is available here 

Introduction to Universal Windows Apps

Visual Studio template for Universal Windows Apps allows developers to build Windows Store App and Phone App in a single Visual Studio solution. This Visual Studio solution includes three projects, project for design and feature experiences unique to Store App, second project for Phone App and third project for shared code.  For more details on Universal Apps template in Visual Studio please click here

Here is the Visual Studio projects for Universal Windows Apps.

UWA_VSOneDrive

The project ending with .Windows is for Store App, project ending with .WindowsPhone is for Phone App and .Shared is for shared code.

In the Shared Project, use following #defines to write specific code for Phone App or Store App

 

#if WINDOWS_PHONE_APP
    // For Windows Phone App
#elif WINDOWS_APP
    // For Windows Store App
#else
    //  Error
#endif

Introduction to OneDrive

Microsoft OneDrive is cloud-based storage solution for all your applications’ end-users' information, files, and folders. For more details please click here.

Use Azure Storage as cloud-based storage solution for all your applications’ files that are common to all end-users. For more details please click here.

Steps to create Universal Windows App

  1. Open Visual Studio

  2. Click on File | New

  3. Select Templates | Visual C# | Store Apps | Universal Apps | Hub App as shown 

    VS_NewProject

  4. Now install NuGet Package for OneDrive

  5. Right click on the .Windows project and select Manage NuGet Packages

  6. In the search textbox type Live SDK and select package created by Microsoft as shown below 

    NuGet_PackageOneDrive

  7. Click on Install button for Live SDK

  8. Now install the OneDrive (Live SDK) NuGet Package on .WindowsPhone project

  9. Right click on the .WindowsPhone project and select Manage NuGet Packages

  10. In the search textbox type Live SDK and click on the install button on package created by Microsoft

  11. Now lets right code for uploading file to OneDrive

  12. Open App.xaml.cs file in the .Shared Project

  13. Copy this below upload function

    
        LiveConnectClient liveClient;
        private async Task<int> UploadFileToOneDrive()
        {
            try
            {
                //  create OneDrive auth client
                var authClient = new LiveAuthClient();
    
                //  ask for both read and write access to the OneDrive
                LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" });
    
                //  if login successful 
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    //  create a OneDrive client
                    liveClient = new LiveConnectClient(result.Session);
    
                    //  create a local file
                    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename", CreationCollisionOption.ReplaceExisting);
    
                    //  copy some txt to local file
                    MemoryStream ms = new MemoryStream();
                    DataContractSerializer serializer = new DataContractSerializer(typeof(string));
                    serializer.WriteObject(ms, "Hello OneDrive World!!");
    
                    using (Stream fileStream = await file.OpenStreamForWriteAsync())
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        await ms.CopyToAsync(fileStream);
                        await fileStream.FlushAsync();
                    }
    
                    //  create a folder
                    string folderID = await GetFolderID("folderone");
    
                    if (string.IsNullOrEmpty(folderID))
                    {
                        //  return error
                        return 0;
                    }
    
                    //  upload local file to OneDrive
                    await liveClient.BackgroundUploadAsync(folderID, file.Name, file, OverwriteOption.Overwrite);
    
                    return 1;
                }
            }
            catch
            {
            }
            //  return error
            return 0;
        }
    
  14. Copy this below code to create a folder on OneDrive

    
        public async Task<string> GetFolderID(string folderName)
        {
            try
            {
                string queryString = "me/skydrive/files?filter=folders";
                //  get all folders
                LiveOperationResult loResults = await liveClient.GetAsync(queryString);
                dynamic folders = loResults.Result;
    
                foreach (dynamic folder in folders.data)
                {
                    if (string.Compare(folder.name, folderName, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        //  found our folder
                        return folder.id;
                    }
                }
    
                //  folder not found
    
                //  create folder
                Dictionary<string, object> folderDetails = new Dictionary<string, object>();
                folderDetails.Add("name", folderName);
                loResults = await liveClient.PostAsync("me/skydrive", folderDetails);
                folders = loResults.Result;
    
                // return folder id
                return folders.id;
            }
            catch
            {
                return string.Empty;
            }
        }
    
  15. Now copy this below download function

    
        public async Task<int> DownloadFileFromOneDrive()
        {
            try
            {
                string fileID = string.Empty;
    
                //  get folder ID
                string folderID = await GetFolderID("folderone");
    
                if (string.IsNullOrEmpty(folderID))
                {
                    return 0; // doesnt exists
                }
    
                //  get list of files in this folder
                LiveOperationResult loResults = await liveClient.GetAsync(folderID + "/files");
                List<object> folder = loResults.Result["data"] as List<object>;
    
                //  search for our file 
                foreach (object fileDetails in folder)
                {
                    IDictionary<string, object> file = fileDetails as IDictionary<string, object>;
                    if (string.Compare(file["name"].ToString(), "filename", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        //  found our file
                        fileID = file["id"].ToString();
                        break;
                    }
                }
    
                if (string.IsNullOrEmpty(fileID))
                {
                    //  file doesnt exists
                    return 0;
                }
    
                //  create local file
                StorageFile localFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename_from_onedrive", CreationCollisionOption.ReplaceExisting);
    
                //  download file from OneDrive
                await liveClient.BackgroundDownloadAsync(fileID + "/content", localFile);
    
                return 1;
            }
            catch
            {
            }
            return 0;
        }
    
  16. Now call these two functions

    
        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
    #if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
    #endif
            int r = await UploadFileToOneDrive();
            if( r== 1)
            {
                await DownloadFileFromOneDrive();
            }
    
            Frame rootFrame = Window.Current.Content as Frame;
    
  17. Run the Windows Store App

  18. Did you get any errors ?

    
    {"Object reference not set to an instance of an object."}
    
       at Microsoft.Live.ResourceHelper.GetString(String name)
       at Microsoft.Live.TailoredAuthClient.<AuthenticateAsync>d__0.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at Microsoft.Live.LiveAuthClient.<ExecuteAuthTaskAsync>d__8.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at UniversalAppOneDrive.App.<UploadFileToOneDrive>d__a.MoveNext()
    
  19. This error usually indicates our current Windows Store App is not associated to an App Name in the store

  20. To associate our current app with the Store, right click on .Windows project, select Store | Associate App with the Store…

  21. Sign in with your developer account and register the app name

  22. Now run the Windows Store App again

  23. This time Microsoft Account UI will ask end user permission to allow your app to access their OneDrive as shown below

  24. onedrive_signin

  25. here is the complete source code

Comments

  • Anonymous
    September 23, 2014
    This is an awsome post. thank you.

  • Anonymous
    November 16, 2014
    Great and very helpfull article! Thanks

  • Anonymous
    December 04, 2014
    I tried loading your file but told it is incompatible with my version of VS. I am using 2013. what version were you using? Thanks

  • Anonymous
    April 05, 2015
    I like the GetFolderID(string folderName) function I think it saved my life live ...  

  • Anonymous
    July 20, 2017
    thanks