4

我需要将数据从我的 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。

我该怎么做?

4

1 回答 1

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。只需在发布文件夹数据请求时注册该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);
}
于 2013-04-10T17:35:40.163 回答