1 ///2 /// 数据存储 3 /// 4 ///5 /// 6 /// 7 /// 8 public static async Task SavaData (T data,string fileName) 9 {10 //创建文件11 try12 {13 StorageFile sFile =await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName,CreationCollisionOption.ReplaceExisting);14 //写入流15 IRandomAccessStream stream = await sFile.OpenAsync(FileAccessMode.ReadWrite);16 17 using (IOutputStream outStream = stream.GetOutputStreamAt(0))18 {19 //序列化数据,并写入数据20 DataContractSerializer serializer = new DataContractSerializer(typeof(T));21 serializer.WriteObject(outStream.AsStreamForWrite(), data);22 await outStream.FlushAsync();//异步刷新数据23 //outStream.Dispose();//异步刷新数据 24 }25 stream.Dispose(); 26 //要把留释放掉否则会出现对同一文件操作的权限问题27 28 }29 catch (Exception error)30 {31 throw new Exception(error.Message);32 }33 }34 35 /// 36 /// 读取数据37 /// 38 /// 39 ///40 public static async Task ReadData (string fileName)41 {42 T data=default(T);43 try44 {45 //获取文件46 StorageFile sFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);47 if (sFile == null) return data;48 //打开一个顺序访问流49 IInputStream inputStream = await sFile.OpenSequentialReadAsync();50 //反序列化51 DataContractSerializer serializer = new DataContractSerializer(typeof(T));52 data = (T)serializer.ReadObject(inputStream.AsStreamForRead());53 }54 catch (Exception error)55 { }56 return data;57 }58 59 /// 60 /// 删除文件 61 /// 62 /// 63 ///64 public static async Task DeleteData(string fileName)65 {66 bool isDelete = false;67 try68 {69 StorageFile sFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);70 await sFile.DeleteAsync();71 isDelete = true;72 }73 catch (Exception)74 { }75 return isDelete;76 }77 78 79 public static async Task WriteTimestamp()80 {81 try82 {83 StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.ReplaceExisting);84 await FileIO.WriteTextAsync(sampleFile, DateTime.Now.ToString());85 }86 catch (Exception e1)87 {88 throw new Exception(e1.Message);89 }90 }
文件存储操作