2013-04-10 49 views
4

我需要备份的数据从我的WP7应用到SkyDrive,这个文件是XML文件。我知道如何连接到SkyDrive以及如何在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复制文件。

我该怎么办?

回答

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); 
} 
+1

大它的工作原理,但我有问题,在指定路径到SkyDrive,如果我用我的/ SkyDrive的那么一切都很正常,但我的文件夹MyData的SkyDrive上,这是地方,我想上传该文件,但如果我使用path my/skydrive/MyData,则应用程序崩溃。我如何指定路径正确? – Earlgray 2013-04-10 20:33:29

+0

这是一个很好的问题,我忘了提及它。这不是文件夹名称,它是文件夹* id *。您必须获取文件夹信息并从结果中提取ID,并在上传时使用该ID。 – Patrick 2013-04-10 23:29:21

+0

thak你,我可以在创建文件夹时获取文件夹ID(如在代码中创建我在第一篇文章中写的文件夹)? – Earlgray 2013-04-11 10:43:39