2013-04-11 66 views
2

我想寫一些數據到我的項目(本地文件到項目)中的現有文件。我用下面的代碼使用StreamWriter後文件空白

 Uri path = new Uri(@"Notes.txt", UriKind.Relative); 

     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 

      using (StreamWriter writefile = new StreamWriter(new IsolatedStorageFileStream(path.ToString(), FileMode.Append, FileAccess.Write,myIsolatedStorage))) 
      { 
       writefile.WriteLine("hi"); 
       writefile.Flush(); 
       writefile.Dispose(); 
      } 
     } 

在執行program.However文件是空白的,不包含任何數據沒有例外/錯誤。

我已經將文件的構建操作設置爲'resource',將內容設置爲'copy if newer'。 只是爲了檢查,我刪除了文件並進行了測試,但它仍然沒有給出任何異常,儘管我試圖在追加模式下打開。

編輯:我在我的開發環境中打開文件來檢查。不過,我後來使用ISETool.exe來檢查文件。但該文件根本沒有創建!以下是更新後的代碼我使用:

Uri path = new Uri(@"Notes.txt", UriKind.Relative); 
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
using (var stream = new IsolatedStorageFileStream(path.ToString(), FileMode.OpenOrCreate, FileAccess.Write, myIsolatedStorage)) 
using (var writefile = new StreamWriter(stream)) 
     { 
      writefile.WriteLine("hi"); 
     } 
+0

你是如何檢查是否該文件有任何數據? – 2013-04-11 03:34:12

+0

我手動打開文件,手動檢查任何數據 – user2210060 2013-04-11 03:43:17

+0

從哪裏?您是否使用IsolatedStorageTool從應用程序下載它? – 2013-04-11 03:44:37

回答

6

編輯

此基礎上您的意見,我覺得你的問題其實是,你誤會了獨立存儲是如何工作的;它將文件存儲在您的手機模擬器圖像之內,這兩者都不是您開發計算機的本機文件系統。

如果您需要從開發計算機訪問該文件,你需要像Windows Phone Power Tools一個實用程序(C/O Alastair Pitts,以上)或the SDK's isetool.exe,如果你不介意的命令行界面。

原帖

兩件事情我跳出:

  1. 你不處置您的IsolatedStorageFileStream
  2. 您應該從IsolatedStorageFile
  3. 獲得您的IsolatedStorageFileStream實例時不需要撥Disposewritefile(這就是using所做的)

試試這個:

using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
using (var stream = isolatedStorage.OpenFile(path.ToString(), FileMode.Append, FileAccess.Write)) 
using (var writefile = new StreamWriter(stream)) 
{ 
    writefile.WriteLine("hi"); 
} 
+0

我試過上面的代碼。同樣的結果:(是否需要對Build操作或內容?或文件的路徑進行任何操作?我將文件放在mainpage.xaml所在的文件夾中。 – user2210060 2013-04-11 03:47:46

+0

請檢查我編輯的問題。當我嘗試將所有文​​件下載到本地驅動器時,下載了一個文件夾「IsolatedStore」。該文件夾根本不包含任何文件「Notes.txt」。 – user2210060 2013-04-11 04:52:45

+0

如果無法寫入文件系統,則會引發異常。您是否嘗試過調試並檢查代碼實際執行?它的確如此,然後嘗試打開文件(在單獨的使用塊中)以查看數據是否可讀。 – 2013-04-11 04:57:33