c# – OneDrive上传/下载到指定目录
作者:互联网
我正在尝试使用Live SDK(v5.6)在我的Windows Phone 8.1 Silverlight应用程序中包含OneDrive的备份/恢复.我可以读/写标准的“me / skydrive”目录,但我正在寻找一种上传/下载到指定目录的方法.我可以创建文件夹,如果它不存在没问题.
我一直在尝试下面没有运气.
var res = await _client.UploadAsync("me/skydrive/mydir", fileName, isoStoreFileStream, OverwriteOption.Overwrite);
我也试过获取目录ID并传入它.
var res = await _client.UploadAsync("me/skydrive/" + folderId, fileName, isoStoreFileStream, OverwriteOption.Overwrite);
相同的错误..我收到’mydir’或者不支持id …
“{request_url_invalid:Microsoft.Live.LiveConnectException:URL包含路径’mydir’,不受支持.”
有什么建议?如果你建议上传同步的答案,你还可以包括我如何从指定的目录下载我的文件?谢谢!
解决方法:
这是一个扩展方法,用于检查是否创建了文件夹,并且:
>如果创建,则返回文件夹ID.
>如果未创建,则创建它并返回文件夹ID.
然后,您可以使用此ID上传到该文件夹并从该文件夹下载.
public async static Task<string> CreateDirectoryAsync(this LiveConnectClient client,
string folderName, string parentFolder)
{
string folderId = null;
// Retrieves all the directories.
var queryFolder = parentFolder + "/files?filter=folders,albums";
var opResult = await client.GetAsync(queryFolder);
dynamic result = opResult.Result;
foreach (dynamic folder in result.data)
{
// Checks if current folder has the passed name.
if (folder.name.ToLowerInvariant() == folderName.ToLowerInvariant())
{
folderId = folder.id;
break;
}
}
if (folderId == null)
{
// Directory hasn't been found, so creates it using the PostAsync method.
var folderData = new Dictionary<string, object>();
folderData.Add("name", folderName);
opResult = await client.PostAsync(parentFolder, folderData);
result = opResult.Result;
// Retrieves the id of the created folder.
folderId = result.id;
}
return folderId;
}
然后你用它作为:
string skyDriveFolder = await CreateDirectoryAsync(liveConnectClient, "<YourFolderNameHere>", "me/skydrive");
现在,skyDriveFolder具有上传和下载时可以使用的文件夹ID.这是一个示例上传:
LiveOperationResult result = await liveConnectClient.UploadAsync(skyDriveFolder, fileName,
fileStream, OverwriteOption.Overwrite);
添加以完成YnotDraw的回答
使用您提供的内容,以下是如何通过指定文件名来下载文本文件.下面不包括是否找不到文件和其他潜在的例外情况,但这里有什么在星星正确对齐时有效:
public async static Task<string> DownloadFileAsync(this LiveConnectClient client, string directory, string fileName)
{
string skyDriveFolder = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive");
var result = await client.DownloadAsync(skyDriveFolder);
var operation = await client.GetAsync(skyDriveFolder + "/files");
var items = operation.Result["data"] as List<object>;
string id = string.Empty;
// Search for the file - add handling here if File Not Found
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == fileName)
{
id = file["id"].ToString();
break;
}
}
var downloadResult= await client.DownloadAsync(string.Format("{0}/content", id));
var reader = new StreamReader(downloadResult.Stream);
string text = await reader.ReadToEndAsync();
return text;
}
在使用中:
var result = await DownloadFile(_client, "MyDir", "backup.txt");
标签:c,live-sdk,onedrive,live-connect-sdk 来源: https://codeday.me/bug/20190716/1477309.html