UWP 打开、保存文件示例

保存文件:

 1 private async void RecDataSaveBtn(object sender, RoutedEventArgs e)
 2 {
 3     string writingData = recvTbx.Text;
 4     FileSavePicker fp = new FileSavePicker();
 5     var filedb = new[] { ".txt"};
 6     fp.FileTypeChoices.Add("DB", filedb);
 7     fp.SuggestedFileName = "savedata" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year;
 8     StorageFile sf = await fp.PickSaveFileAsync();
 9     if (sf != null)
10     {
11         using (StorageStreamTransaction transaction = await sf.OpenTransactedWriteAsync())
12         {
13             using (DataWriter dataWriter = new DataWriter(transaction.Stream))
14             {
15                 dataWriter.WriteString(writingData);
16                 transaction.Stream.Size = await dataWriter.StoreAsync();
17                 await transaction.CommitAsync();
18             }
19         }
20     }
21 }

 

打开文件:

 1 private async void OpenFileBtn(object sender, RoutedEventArgs e)
 2 {
 3     FileOpenPicker fop = new FileOpenPicker();
 4     fop.FileTypeFilter.Add(".txt");
 5     fop.FileTypeFilter.Add(".dat");
 6 
 7     StorageFile sf=await fop.PickSingleFileAsync();
 8     if (sf != null)
 9     {
10         using (IRandomAccessStream readStream = await sf.OpenAsync(FileAccessMode.Read))
11         {
12             using (DataReader dataReader = new DataReader(readStream))
13             {
14                 UInt64 size = readStream.Size;
15                 if (size <= UInt32.MaxValue)
16                 {
17                     UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
18                     string fileContent = dataReader.ReadString(numBytesLoaded);
19                     sendTbx.Text = fileContent;
20                 }
21             }
22         }
23     }
24 }

 

posted @ 2017-03-08 21:40  茄阁云云  阅读(1276)  评论(0编辑  收藏  举报