2013-11-09 42 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()); 
}