Reputation: 41
I am trying to download a file from OneDrive using the OneDrive SDK. I have a UWP app that I have created.
I have connected to my OneDrive account but don't comprehend what to do from there. There are a lot of answers out there but it seems they don't pertain to the new OneDrive SDK.
I want to do this method in C#.
StorageFile downloadedDBFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("\\shared\\transfers\\" + App.dbName, CreationCollisionOption.ReplaceExisting);
Item item = await oneDriveClient.Drive.Root.ItemWithPath("Apps/BicycleApp/ALUWP.db").Request().GetAsync();
oneDriveClient connects fine. I even get the "item". As you can see it is in a sub directory on my OneDrive.
I have created a local file, in a sub directory, called downloadedDBFile so I can copy the contents of the OneDrive file to.
What do I do from here?
I have uploaded file to OneDrive using this method with no problem.
IStorageFolder sf = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("shared\\transfers");
var folder = ApplicationData.Current.LocalFolder;
var files = await folder.GetFilesAsync();
StorageFile dbFile = files.FirstOrDefault(x => x.Name == App.dbName);
await dbFile.CopyAsync(sf, App.dbName.ToString(), NameCollisionOption.ReplaceExisting);
StorageFile copiedFile = await StorageFile.GetFileFromPathAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, "shared\\transfers\\" + App.dbName));
var randomAccessStream = await copiedFile.OpenReadAsync();
Stream stream = randomAccessStream.AsStreamForRead();
var item = await oneDriveClient.Drive.Special.AppRoot.Request().GetAsync();
txtOutputText.Text = "Please wait. Copying File";
using (stream){var uploadedItem = await oneDriveClient.Drive.Root.ItemWithPath("Apps/BicycleApp/ALUWP.db").Content.Request().PutAsync<Item>(stream);}
Thanks in advance
Upvotes: 0
Views: 1788
Reputation: 684
The Item object you are getting back isn't the file contents, it's most probably information about the file. Instead, you need to use the Content property to get the file contents as a stream, which you can then copy to a file. The code looks like this:
using (var downloadStream = await oneDriveClient.Drive.Root.ItemWithPath("Apps/BicycleApp/ALUWP.db").Content.Request().GetAsync())
{
using (var downloadMemoryStream = new MemoryStream())
{
await downloadStream.CopyToAsync(downloadMemoryStream);
var fileBytes = downloadMemoryStream.ToArray();
await FileIO.WriteBytesAsync(downloadedDBFile, fileBytes);
}
}
Notice the .Content on the call to OneDrive, which returns a stream instead of the Item object.
Upvotes: 5