public static async Task SaveFileAsync(string FileName, T data)
{
MemoryStream memStream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memStream, data);
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName,
CreationCollisionOption.ReplaceExisting);
using (Stream stream = await file.OpenStreamForWriteAsync())
{
memStream.Seek(0, SeekOrigin.Begin);
await memStream.CopyToAsync(stream);
await stream.FlushAsync();
}
}
public static async Task<T> RestoreFileAsync(string FileName)
{
T result = default(T);
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(FileName);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
result = (T)serializer.ReadObject(inStream.AsStreamForRead());
return result;
}
}
catch (FileNotFoundException)
{
return default(T);
}
}
我正在使用此代码来保存和检索我的数据,它工作正常。有时我启动我的应用程序,突然所有数据都被删除了,我真的不知道为什么。我尝试DataContractJsonSerializer
将其保存为 .txt 文件,但仍然是同样的问题。没有异常或错误。我还检查了它自己的文件,.xml 和 .txt 删除了所有内容。我其实很困惑。