2013-04-10 51 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