我正在编写我的第一个 Windows Phone 8 应用程序,我只是在尝试一些简单的东西。读/写文件。这是我的两种方法:
public static async Task<Week> Load()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
try
{
StorageFile mealsFile = await folder.GetFileAsync("file.txt");
if (mealsFile != null)
{
using (var stream = await mealsFile.OpenAsync(FileAccessMode.Read))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
var w = (List<MyTypeHere>)serializer.ReadObject(stream.AsStreamForRead());
if (w != null)
MyWeek.WeekList = new ObservableCollection<MyTypeHere>(w);
}
}
}
catch(FileNotFoundException fEx)
{
MyWeek = new Week();
}
return MyWeek;
}
public static async Task<bool> Save()
{
try
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile mealsFile = await folder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting);
using (var stream = await mealsFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var sw = stream.GetOutputStreamAt(0))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
serializer.WriteObject(sw.AsStreamForWrite(), MyWeek.WeekList.ToList());
await sw.FlushAsync();
}
}
MyWeek = null;
return true;
}
catch(Exception ex)
{
return false;
}
}
我正在调用 Save(带断点,它可以正常工作),然后调用 Load(带断点)来加载文件,文件存在并填充我的对象图。
当我关闭应用程序并重新启动它时,会捕获 FileNotFoundException 的捕获。为什么?
从我可以看到本地文件夹应该是持久化文件。我所缺少的显然应该是显而易见的......
谢谢
编辑:
我正在使用 Windows Phone 模拟器,当我关闭它并在 Visual Studio 上按 F5 时,该文件不再存在。