2014-01-18 25 views
1

我試圖將RichEditBox的內容保存到我的應用臨時文件夾,但是我無法使其工作。將RichText文檔保存到Windows應用商店應用中的臨時文件夾

這裏是工作的代碼,將文件保存到磁盤上,通過保存文件選擇器:

// [code for savePicker. Not relevant because that all works fine] 
StorageFile file = await savePicker.PickSaveFileAsync(); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

這裏的工作代碼到一個txt文件保存到臨時存儲

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.txt", 
         CreationCollisionOption.ReplaceExisting); 
await FileIO.WriteTextAsync(file, "some text"); 

所以當我結合這些將RTF內容保存到臨時文件夾,這是我寫的:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf", 
         CreationCollisionOption.ReplaceExisting); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

This不起作用。我在第二行StorageFile file = etc上收到訪問被拒絕錯誤(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))。然而,這段代碼在上面的第二個塊中執行得很好。看來,當我跟着它與file.OpenAsync它會引發錯誤。有人可以在這裏指出我正確的方向嗎?這與await有關嗎?

編輯:我已經接受並由Damir Arh提出答案,因爲它是對這個問題的正確解決方案。我的解決方法爲我解決了這個問題,但Damir Arh的回答解決了問題的根本原因,當然總是更好。

回答

3

的代碼塊應該只是罰款;我甚至測試過它,只是爲了確保:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf", 
         CreationCollisionOption.ReplaceExisting); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

您錯誤地標識了,爲什麼它失敗。 CreateFileAsync不能失敗,因爲它後面跟着OpenAsync;後者在失敗時甚至沒有開始執行。

最可能的原因是您已經從Stream打開,您沒有正確關閉。即使使用您在答案中發佈的代碼,這仍然會發生。

我建議您使用CreationCollisionOption.GenerateUniqueName而不是CreationCollisionOption.ReplaceExisting。這樣,如果由於某種原因它不能與原始文件名一起創建具有不同名稱的文件。

還要確保在完成寫作後正確關閉流。由於IRandomAccessStream實現了IDisposable,因此當您不再需要時,您應該始終致電Dispose。或者甚至更好:把它放在一個using區塊,它會爲你做到這一點。

下面是應用了這兩個變化的代碼:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf", 
          CreationCollisionOption.GenerateUniqueName); 
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) 
{ 
    Editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 
    await stream.FlushAsync(); 
} 
+0

謝謝,我想我是基於這個想出來的:這是自動保存功能的一部分,每90秒,因爲我不想每次測試都要等待90秒,所以我將它設置爲在應用程序啓動後1秒開始,這當然也意味着它每秒發射一次! – roryok

0

,我想出了一個解決辦法:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf", 
         CreationCollisionOption.ReplaceExisting); 
string rtfcontent = ""; 
editor.Document.GetText(TextGetOptions.FormatRtf, out rtfcontent); 
await FileIO.WriteTextAsync(file, rtfcontent); 
+0

有時我可以張貼到計算器,我會找出自己坐在後一個問題了幾個小時,然後一兩分鐘。然後,看起來我只是沒有在發佈之前花費任何時間進入它! =(我不確定是否應該刪除這些文件或將它們留下,但是誰知道 - 他們可能會使某人受益 – roryok

相關問題