Silverlight で Windows Phone 7 アプリを作成しています。の使用に問題があり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 は、 の 1 回の呼び出しで書き込んだものだけですwriteToFile()
。これが私の読む方法です:
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;
}
ここで何が間違っているのでしょうか?ファイルへの書き込みが間違っていますか? 読み戻すことができる唯一のデータは、最初の書き込みからのものであると確信しています。
更新: 2 つの呼び出しを追加しまし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
私はさらに数回テストを実行しました。最初のアイテムだけが読み返されていると確信しています。