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.
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
Open Visual Studio
Click on File | New
Select Templates | Visual C# | Store Apps | Universal Apps | Hub App as shown
Now install NuGet Package for OneDrive
Right click on the .Windows project and select Manage NuGet Packages
In the search textbox type Live SDK and select package created by Microsoft as shown below
Click on Install button for Live SDK
Now install the OneDrive (Live SDK) NuGet Package on .WindowsPhone project
Right click on the .WindowsPhone project and select Manage NuGet Packages
In the search textbox type Live SDK and click on the install button on package created by Microsoft
Now lets right code for uploading file to OneDrive
Open App.xaml.cs file in the .Shared Project
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; }
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; } }
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; }
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;
Run the Windows Store App
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()
This error usually indicates our current Windows Store App is not associated to an App Name in the store
To associate our current app with the Store, right click on .Windows project, select Store | Associate App with the Store…
Sign in with your developer account and register the app name
Now run the Windows Store App again
This time Microsoft Account UI will ask end user permission to allow your app to access their OneDrive as shown below
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! ThanksAnonymous
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? ThanksAnonymous
April 05, 2015
I like the GetFolderID(string folderName) function I think it saved my life live ...Anonymous
July 20, 2017
thanks