从文本文件中读取应用程序时崩溃
问题描述:
我试图通过从文本文件中读取每行的名称来填充List<Image>
。该文本文件如下所示:从文本文件中读取应用程序时崩溃
image0
image1
image2
image
...
以下代码使我的程序完全崩溃,并使Visual Studio冻结。
int counter = 0;
string line = string.Empty;
StreamReader file = new StreamReader("ItemFile.txt");
while ((line = file.ReadLine()) != null)
{
imageCollection.Add(new Image());
imageCollection[counter].Source = new BitmapImage(new Uri("Images/" + line + ".png", UriKind.Relative));
}
答
您不能在WP7上使用标准的读/写机制。你必须使用IsolatedStorage类来做到这一点:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("ItemFile.txt", FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{ //Visualize the text data in a TextBlock text
while ((line = reader .ReadLine()) != null)
{
imageCollection.Add(new Image());
imageCollection[counter].Source = new BitmapImage(new Uri("Images/" + line + ".png", UriKind.Relative));
}
}
如果你想从它在安装过程中添加到设备作为项目的一部分,看看这个问题,文件读取文本:How to read files from project folders?
+0
我在IsolatedStorageFileStream中得到一个不允许的操作我使用上面的代码。 – Subby
我认为,在WP7,你需要使用IsolatedStorage机制来读取/写入文件。 – ZafarYousafi
是否有抛出的异常?请注意,加载大图像的列表预计会很慢。 – Vlad
如果您的文件位于独立存储中,则应该从IsolatedStorage中读取它们。 [该指南可能会对你有所帮助] –