使用 OneDrive SDK 从 OneDrive 下载文件

7VN*_*VNT 0 sdk onedrive uwp

我正在尝试使用 OneDrive SDK 从 OneDrive 下载文件。我有一个我创建的 UWP 应用程序。

我已连接到我的 OneDrive 帐户,但不知道从那里开始做什么。有很多答案,但似乎它们与新的 OneDrive SDK 无关。

我想在 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();
Run Code Online (Sandbox Code Playgroud)

oneDriveClient 连接正常。我什至得到了“项目”。如您所见,它位于我的 OneDrive 上的子目录中。

我在子目录中创建了一个本地文件,名为downloadedDBFile,以便我可以将 OneDrive 文件的内容复制到。

我从这里做什么?

我已使用此方法将文件上传到 OneDrive,没有任何问题。

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);}
Run Code Online (Sandbox Code Playgroud)

提前致谢

小智 5

您返回的 Item 对象不是文件内容,它很可能是有关文件的信息。相反,您需要使用 Content 属性以流的形式获取文件内容,然后您可以将其复制到文件中。代码如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意调用 OneDrive 时的 .Content,它返回一个流而不是 Item 对象。