2014-03-02 52 views
0

我想用Web中的文本文件替換存在爲IsolatedStorageFile的文本文件。如何替換.txt文件Windows Phone 8

var store = IsolatedStorageFile.GetUserStoreForApplication() 
IsolatedStorageFileStream rootFile = store.CreateFile("InTheRoot.txt"); 
IsolatedStorageFile.CopyFile(rootFile, "http://example.com/test.txt" , true); 

這裏的錯誤是什麼?謝謝。

+1

爲什麼不直接使用'File.Copy(rootfile的,「http://example.com/test.txt」,真);'?此代碼不起作用?任何錯誤或異常消息? –

+0

您需要提供更多信息 –

+0

非靜態字段,方法或屬性'System.IO.IsolatedStorage.IsolatedStorageFile.CopyFile(string,string,bool)需要對象引用 - 出現此錯誤 – Tany3450

回答

0

不能使用IsolatedStorageFile.CopyFile()來從網上下載的文件。

的快速和骯髒的方法是使用一個隱藏的WebBrowser控件:

XAML

<phone:WebBrowser x:Name="Browser" Navigated="Browser_Navigated" Visibility="Collapsed"></phone:WebBrowser> 
<TextBlock x:Name="Text"></TextBlock> 

C#

public MainPage() 
    { 
     InitializeComponent(); 

     Browser.Navigate(new Uri("http://example.com/test.txt")); 
    } 

    private void Browser_Navigated(object sender, NavigationEventArgs e) 
    { 
     var store = IsolatedStorageFile.GetUserStoreForApplication(); 
     var filename = "InTheRoot.txt"; 

     if (store.FileExists(filename)) store.DeleteFile(filename); 

     using (var stream = store.CreateFile(filename)) 
     { 
      using (var writer = new StreamWriter(stream)) 
      { 
       writer.Write(Browser.SaveToString()); 
      } 
     } 

     using (var file = store.OpenFile(filename, FileMode.Open)) 
     { 
      using(var reader = new StreamReader(file)) 
      { 
       Text.Text = reader.ReadToEnd(); 
      } 
     } 
    } 

有這樣做的主要問題是,它包裝了文本,文件內容在<HTML> <BODY>元素。

這不是真正的建議,但它會讓你啓動和運行。

更好的方法來檢索網頁內容使用BackgroundTransferRequest詳細的herehere

+0

同樣的錯誤:(>>>>> var store = IsolatedStorageFile.GetUserStoreForApplication(); store.CopyFile(「http://cr.yp.to/proto/netstrings.txt」,「InTheRoot.txt」,true) ; – Tany3450

+0

我會盡快檢查,現在有點忙,謝謝! – Tany3450

0

改變這一行:

IsolatedStorageFile.CopyFile(rootFile, "http://example.com/test.txt" , true); 

這樣:

store.CopyFile("InTheRoot.txt", "http://example.com/test.txt" , true); 

將修復 「一個對象引用是所必需的非靜態字段,方法或屬性」 的錯誤,並且下一個錯誤「無法從'System.IO.IsolatedStorage.IsolatedStorageFileStream'轉換爲'字符串'」。因爲第一個參數的預期類型是string而不是IsolatedStorageFileStream

[For Reference]

+0

是的謝謝你的工作。它現在正在編譯,但現在正在崩潰。我用一個有效的網站替換了.txt文件。 >> mscorlib.ni.dll中發生類型爲「System.IO.IsolatedStorage.IsolatedStorageException」的異常,但未在用戶代碼中處理。附加信息:不允許操作。 – Tany3450

+0

您需要切換文件名,source是第一個參數。目的地是第二位。您也不需要先創建文件。 –

+0

嗨邁克爾。我已經嘗試過,但同樣的錯誤。 – Tany3450