2013-11-09 94 views
0

我必須在Windows Phone 7.1的移動應用程序中讀取文本文件。我寫我的代碼:在WP7中讀取文件

IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication(); 
StreamReader Reader = null; 
try 
{ 
Reader = new StreamReader(new IsolatedStorageFileStream("folder\\file.txt", FileMode.Open, fileStorage)); 
string textFile = Reader.ReadToEnd(); 

textBlock.Text = textFile; 
Reader.Close(); 
} 
catch 
{ 
MessageBox.Show("File it not created"); 
} 

所有的時候,當我試着讀這個文件,應用程序顯示我的MessageBox文本「文件它沒有創建」。我不知道爲什麼應用程序找不到我的文件。

回答

0

還有別的東西創建文件?如果不是,這是預期的行爲,因爲路徑中沒有文件。在IsolatedStorageFileStream構造函數中,您傳遞了FileMode.Open,它表示「操作系統應該打開一個現有文件。打開文件的能力取決於FileAccess枚舉指定的值。如果出現System.IO.FileNotFoundException異常,則會拋出System.IO.FileNotFoundException異常文件不存在。」如果需要創建該文件,請嘗試FileMode.CreateNew,它表示「操作系統應該創建一個新文件,這需要FileIOPermissionAccess.Write權限,如果文件已經存在,則拋出IOException異常」或FileMode.CreateOrOpen

另外,您可能需要考慮類似於以下內容來代替您的抓取。它應該爲您提供更多信息,使調試更快:

catch (Exception ex) 
{ 
    MessageBox.Show("Exception opening file: " + ex.ToString()); 
}