上一篇文章中,我們討論了打開文件的UI,現在,我們繼續探索一下保存文件的UI組件,
同樣道理,也是很簡單的。
這回我們用到Windows.Storage.Pickers.FileSavePicker類,與上次打開文件的使用方法基本
一致。當我們調用PickSaveFileAsync方法後,如果用戶進行了確認而不是取消,就會返回一
個StorageFile實例,我們的寫入操作就可以圍繞StorageFile對象展開了。
下面我們來用實例來說明一下吧。
第1步,啓動VS,新建一個空白頁面的Windows Store應用程序。
第2步,對主頁MainPage.xaml我們作以下佈局。
<Page
x:Class="SaveFilePickerExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SaveFilePickerExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Canvas Background="{StaticResource AppBarBackgroundThemeBrush}">
<TextBox Name="txtContent" Canvas.Left="6" Canvas.Top="11"
Width="1279" Height="365" TextWrapping="Wrap" FontSize="18"/>
<Button Content="保存到文件" Canvas.Left="54" FontSize="24"
Canvas.Top="414" Padding="25,17" Click="btnSave_Click"/>
<TextBlock Name="Msg" FontSize="20" Canvas.Left="280" Canvas.Top="450"/>
</Canvas>
</Page>
第3步,切換到代碼視圖,完成下面代碼。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Storage.Pickers;
namespace SaveFilePickerExample
{
/// <summary>
/// 可用於自身或導航至 Frame 內部的空白頁。
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
if (this.txtContent.Text.Equals(string.Empty))
{
return;
}
FileSavePicker picker = new FileSavePicker();
// 提交按鈕上顯示的文本
picker.CommitButtonText = "保存";
// 支持的文件類型
picker.FileTypeChoices.Add("文本文件", new string[] { ".txt" });
// 默認顯示的目錄
picker.SuggestedStartLocation = PickerLocationId.Desktop;
// 顯示UI並返回內容
StorageFile file = await picker.PickSaveFileAsync();
// 向文件寫入內容
if (file != null)
{
await FileIO.WriteTextAsync(file, txtContent.Text, Windows.Storage.Streams.UnicodeEncoding.Utf8);
this.Msg.Text = "文件已保存。";
}
}
}
}
設置CommitButtonText屬性,就是提交按鈕上顯示的文本,比如上面代碼中,我們設置了
“保存”,就會如下圖所示的結果。
FileTypeChoices屬性設置支持的文件類型,它是一個字典集合,鍵就是用於說明的簡短文本,
值是一個列表值,可以包含多個擴展名。如:
Jpeg圖片 ----> .jpg .jpeg音頻文件 ----> .mp3 .wav .wma
本例的執行結果如下面圖所示。
當文件保存後,我們再用記事打開剛剛保存的文件,就能看到對應的文本內容。