2013-02-15 61 views
2
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删除所有内容。 其实我很困惑。winRT存储文件问题

+0

您是否在unittests中看到过这种行为?在我的场景中,他们总是得到一个新的本地文件夹内容被删除后ApplicationData.Current.LocalFolder是否发生变化? 编写简单文本时有问题吗? – 2013-02-17 12:09:44

+0

是本地文件夹在内容被删除时发生更改,我没有任何其他问题,没有错误没有例外,有时并不总是只是删除它。 – 2013-02-18 07:33:57

+0

挖掘周围后,如果我改变了appxmanifest中的任何东西都会重新安装,但这也不是问题。 我不断测试应用程序,是否因为我经常从Visual Studio不时运行应用程序? – 2013-02-18 07:37:08

回答

2

像这样的问题通常是一个锁定问题。当应用程序关闭并且生成的文件为空时,您将打开该流。这是预料之中的。有时候,你会在多个单元测试中使用异步操作来创建竞争条件。这是预料之中的。你可以通过锁定线程来解决这个问题。

阅读这篇文章,看看它可以帮助你:http://blog.jerrynixon.com/2013/02/walkthrough-locking-asynchronous-file.html我真的很希望它。