win8 文件读取操作----模版操作
1 /// <summary> 2 /// 数据存储 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="data"></param> 6 /// <param name="fileName"></param> 7 /// <returns></returns> 8 public static async Task SavaData<T>(T data,string fileName) 9 { 10 //创建文件 11 try 12 { 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 /// <summary> 36 /// 读取数据 37 /// </summary> 38 /// <param name="fileName"></param> 39 /// <returns></returns> 40 public static async Task<T> ReadData<T>(string fileName) 41 { 42 T data=default(T); 43 try 44 { 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 /// <summary> 60 /// 删除文件 61 /// </summary> 62 /// <param name="fileName"></param> 63 /// <returns></returns> 64 public static async Task<bool> DeleteData(string fileName) 65 { 66 bool isDelete = false; 67 try 68 { 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 try 82 { 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 }
文件存储操作