我正在建立一个Windows 7应用程序在Silverlight。我在使用IsolatedStorageFile时遇到了困难。
以下方法应该将一些数据写入文件:
private static void writeToFile(IList<Story> stories)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = storage.OpenFile(STORIES_FILE, FileMode.Append))
{
using (StreamWriter writer = new StreamWriter(stream))
{
StringBuilder toJson = new StringBuilder();
IList<StoryJson> storyJsons = (from story in stories
where !storageStories.Contains(story)
select story.ToStoryJson()).ToList();
writer.Write(JsonConvert.SerializeObject(storyJsons));
}
}
#if DEBUG
StreamReader reader = new StreamReader(storage.OpenFile(STORIES_FILE, FileMode.Open));
string contents = reader.ReadToEnd();
#endif
}最后的DEBUG是让我检查数据是否正在写入。我已经核实过了。这种方法称为6+时间。每次都会追加更多的数据。
但是,当我阅读数据时,我得到的唯一JSON是我用one call of writeToFile()编写的JSON。下面是我的阅读方法:
private static IList<Story> storageStories;
private static IList<Story> readFromStorage()
{
if (storageStories != null)
{
return storageStories;
}
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
if (! storage.FileExists(STORIES_FILE))
{
storage.CreateFile(STORIES_FILE);
storageStories = new List<Story>();
return storageStories;
}
string contents;
using (IsolatedStorageFileStream stream = storage.OpenFile(STORIES_FILE, FileMode.OpenOrCreate))
{
using (StreamReader reader = new StreamReader(stream))
{
contents = reader.ReadToEnd();
}
}
JsonSerializer serializer = new JsonSerializer();
storageStories = JArray.Parse(contents).Select(storyData => storyOfJson(serializer, storyData)).ToList();
return storageStories;
}我在这里做错了什么?我是不是写错了文件?我非常肯定,唯一能够被读取的数据是第一次写入的数据。
Update:我添加了两个Flush()调用,但它崩溃了:
private static void writeToFile(IList<Story> stories)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = storage.OpenFile(STORIES_FILE, FileMode.Append))
{
using (StreamWriter writer = new StreamWriter(stream))
{
StringBuilder toJson = new StringBuilder();
IList<StoryJson> storyJsons = (from story in stories
where !storageStories.Contains(story)
select story.ToStoryJson()).ToList();
writer.Write(JsonConvert.SerializeObject(storyJsons));
writer.Flush();
}
// FAILS
// "Cannot access a closed file." {System.ObjectDisposedException}
stream.Flush();
}
}如果我注释掉了stream.Flush(),而离开了writer.Flush(),我也会遇到同样的问题。
更新2:我添加了一些打印语句。看起来所有的东西都被序列化了:
Serializing for VID 43
Serializing for VID 17
Serializing for VID 6
Serializing for VID 33
Serializing for VID 4
Serializing for VID 5
Serializing for VID 3但实际上只有第一组正在被读取:
Deserializing stories with vid: 43我又做了几次测试。我敢肯定,只有第一项才会被回读。
发布于 2010-11-04 09:04:13
乍一看,听起来您的流数据没有被刷新到磁盘。
您可能认为using块在Disposes流时将执行刷新。然而,我发现情况并不总是这样,有时最好在最后强制使用Flush()。
我记得最近在一个代码库中,我们从一个微软团队收到了一个移植到WP7的代码库,他们在强迫一个Flush。我最初对此提出了质疑,认为Dispose应该处理这个问题,然而,由于它是工作的,而且我们的期限很短,我没有进一步调查它。
放手看看会发生什么..。:)
发布于 2010-11-25 21:38:52
您是否尝试过显式地调用
writer.Close()而不是依赖writer.Dispose()
https://stackoverflow.com/questions/4090679
复制相似问题