我需要将我的WP7应用程序中的数据备份到Skydrive,此文件是xml文件。我知道如何连接到skydrive以及如何在skydrive上创建文件夹:
try
{
var folderData = new Dictionary<string, object>();
folderData.Add("name", "Smart GTD Data");
LiveConnectClient liveClient = new LiveConnectClient(mySession);
liveClient.PostAsync("me/skydrive", folderData);
}
catch (LiveConnectException exception)
{
MessageBox.Show("Error creating folder: " + exception.Message);
}
但我不知道如何将文件从隔离存储复制到skydrive。
我该怎么做?
答案 0 :(得分:5)
这很简单,您可以使用liveClient.UploadAsync
方法
private void uploadFile(LiveConnectClient liveClient, Stream stream, string folderId, string fileName) {
liveClient.UploadCompleted += onLiveClientUploadCompleted;
liveClient.UploadAsync(folderId, fileName, stream, OverwriteOption.Overwrite);
}
private void onLiveClientUploadCompleted(object sender, LiveOperationCompletedEventArgs args) {
((LiveConnectClient)sender).UploadCompleted -= onLiveClientUploadCompleted;
// notify someone perhaps
// todo: dispose stream
}
您可以从IsolatedStorage获取一个流并像这样发送
public void sendFile(LiveConnectClient liveClient, string fileName, string folderID) {
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
Stream stream = storage.OpenFile(filepath, FileMode.Open);
uploadFile(liveClient, stream, folderID, fileName);
}
}
请注意,上传流时需要使用文件夹ID 。由于您正在创建文件夹,因此您可以在完成文件夹创建时获取此ID。只需在发布folderData请求时注册PostCompleted
事件。
这是一个例子
private bool hasCheckedExistingFolder = false;
private string storedFolderID;
public void CreateFolder() {
LiveConnectClient liveClient = new LiveConnectClient(session);
// note that you should send a "liveClient.GetAsync("me/skydrive/files");"
// request to fetch the id of the folder if it already exists
if (hasCheckedExistingFolder) {
sendFile(liveClient, fileName, storedFolderID);
return;
}
Dictionary<string, object> folderData = new Dictionary<string, object>();
folderData.Add("name", "Smart GTD Data");
liveClient.PostCompleted += onCreateFolderCompleted;
liveClient.PostAsync("me/skydrive", folderData);
}
private void onCreateFolderCompleted(object sender, LiveOperationCompletedEventArgs e) {
if (e.Result == null) {
if (e.Error != null) {
onError(e.Error);
}
return;
}
hasCheckedExistingFolder = true;
// this is the ID of the created folder
storedFolderID = (string)e.Result["id"];
LiveConnectClient liveClient = (LiveConnectClient)sender;
sendFile(liveClient, fileName, storedFolderID);
}