1、Creating a file :
在本例中创建一个新的名为 "sample.dat" 的文件。这个文件创建在文档文件 (document library) 夹下。
页面中的 xaml :
<Button Grid.Row="1" x:Name="CreateFileButton" Content="Create 'sample.dat'" Click="CreateFileButton_Click"/>
相应的 C# :
public StorageFile sampleFile = null; public const string filename = "sample.dat"; //创建一个新文件 private async void CreateFileButton_Click(object sender, RoutedEventArgs e) { // 获取文档库。 StorageFolder storageFolder = KnownFolders.DocumentsLibrary; // 在当前文件夹中新建文件,并指定如果文件的名称与当前文件夹中已有文件重复时进行什么操作。 sampleFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); }
2、Writing and reading text in a file :
向 1、 中创建的文件写入文本,在下面的文本框中写入一些文本,点击 “Write” 按钮。
然后,点击 “Read” 按钮把文本从中读出来。
输入文本,点击 Write:
点击 Read 显示结果 :
页面的 xaml :
//写入文本 <TextBox x:Name="InputTextBox" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/> <Button x:Name="WriteTextButton" Content="Write" Click="WriteTextButton_Click"/> <Button x:Name="ReadTextButton" Content="Read" Click="ReadTextButton_Click"/> //显示结果 <TextBlock x:Name="OutputTextBlock" TextWrapping="Wrap"/>
相应的 C# :
向 1、中的 sampleFile 文件写入文本
// sampleFile 文件为 1、 中创建的放在 文档文件夹下 private async void WriteTextButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { // 将文本写入指定文件。 await FileIO.WriteTextAsync(file, userContent); OutputTextBlock.Text = "The following text was written to '"
+ file.Name + "':" + Environment.NewLine + Environment.NewLine + userContent; } else { OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again."; } } } catch (FileNotFoundException) { //文件打开失败 } }
读取文本:
private async void ReadTextButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { string fileContent = await FileIO.ReadTextAsync(file); OutputTextBlock.Text = "The following text was read from '"
+ file.Name + "':" + Environment.NewLine + Environment.NewLine + fileContent; } } catch (FileNotFoundException) { //文件不存在 } }
3、Writing and reading bytes in a file :
和 2、中的操作类似,只是把 文本内容转化成二进制进行读写。操作截图、显示结果和 2、相同。
//输入文本 <TextBox x:Name="InputTextBox" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/> <Button x:Name="WriteBytesButton" Content="Write" Click="WriteBytesButton_Click"/> <Button x:Name="ReadBytesButton" Content="Read" Click="ReadBytesButton_Click"/> //显示结果 <TextBlock x:Name="OutputTextBlock" TextWrapping="Wrap"/>
相应的 C# 方法 :
将二进制文本写入文件:
private async void WriteBytesButton_Click(object sender, RoutedEventArgs e) { try { // 1、中的文件 sampleFile StorageFile file = sampleFile; if (file != null) { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { IBuffer buffer = GetBufferFromString(userContent);
// 从缓冲区将数据写入指定文件。 await FileIO.WriteBufferAsync(file, buffer);
OutputTextBlock.Text = "The following "
+ buffer.Length + " bytes of text were written to '" + file.Name + "':"
+ Environment.NewLine + Environment.NewLine + userContent; } } } catch (FileNotFoundException) { //文件不存在 } } private IBuffer GetBufferFromString(String str) { // 提供输入和输出流中存储在内存而不是磁盘中的数据的随机访问。 using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { using (DataWriter dataWriter = new DataWriter(memoryStream)) { // 将字符串值写入输出流。 dataWriter.WriteString(str); // 分离与数据编写器关联的缓冲区。 // 返回结果: 分离的缓冲区。 return dataWriter.DetachBuffer(); } } }
从文件中读取二进制文本:
private async void ReadBytesButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { IBuffer buffer = await FileIO.ReadBufferAsync(file); using (DataReader dataReader = DataReader.FromBuffer(buffer)) { string fileContent = dataReader.ReadString(buffer.Length); OutputTextBlock.Text = "The following " + buffer.Length
+ " bytes of text were read from '" + file.Name + "':"
+ Environment.NewLine + Environment.NewLine + fileContent; } } } catch (FileNotFoundException) { //文件不存在 } }
4、Writing and reading using a stream :
使用 stream 向 sample.dat 文件中写入文本。操作、结果 和 2、类似。
xaml 页面 :
//用户输入文本 <TextBox x:Name="InputTextBox" IsReadOnly="false" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/> <Button x:Name="WriteToStreamButton" Content="Write" Click="WriteToStreamButton_Click"/> <Button x:Name="ReadFromStreamButton" Content="Read" Click="ReadFromStreamButton_Click"/>
输出结果:
<TextBlock x:Name="OutputTextBlock" TextWrapping="Wrap"/>
相应的 C# 事件 :
用流向文件中写数据:
private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(userContent); // 将缓冲区中的数据提交到备份存储区。 transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file await transaction.CommitAsync(); OutputTextBlock.Text = "The following text was written to '"
+ file.Name + "' using a stream:" + Environment.NewLine + userContent; } } } } } catch (FileNotFoundException) { //文件不存在 } }
private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { // 在文件中打开一个随机访问流。 using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read)) { using (DataReader dataReader = new DataReader(readStream)) { //获取或设置随机访问流的大小。
UInt64 size = readStream.Size;
//表示 System.UInt32 的最大可能值。 此字段为常数。
MaxValue = 4294967295;
if (size <= UInt32.MaxValue) { // 从输入流加载数据。 UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
// 从输入流中读取字符串值。 string fileContent = dataReader.ReadString(numBytesLoaded); OutputTextBlock.Text = "The following text was read from '"
+ file.Name + "' using a stream:" + Environment.NewLine + fileContent; } else { OutputTextBlock.Text = "File " + file.Name +
" is too big for LoadAsync to load in a single chunk. Files
larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync."; } } } } } catch (FileNotFoundException) { //文件不存在 } }
5、Displaying file properties :
本例将读取并显示 2、 中 sample.dat 文件的属性
操作截图:
显示结果 :
页面的 xaml :
<Button Grid.Row="1" x:Name="ShowPropertiesButton" Content="Show Properties" Click="ShowPropertiesButton_Click"/>
<TextBlock x:Name="OutputTextBlock" TextWrapping="Wrap"/>
相应的 C# 代码 :
static readonly string dateAccessedProperty = "System.DateAccessed"; static readonly string fileOwnerProperty = "System.FileOwner"; private async void ShowPropertiesButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = rootPage.sampleFile; if (file != null) { // Get top level file properties StringBuilder outputText = new StringBuilder(); outputText.AppendLine("File name: " + file.Name); outputText.AppendLine("File type: " + file.FileType); // Get basic properties // 提供对基本的属性的访问,如上次对项修改的大小和日期(如文件或文件夹)。 BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
outputText.AppendLine("File size: " + basicProperties.Size + " bytes"); outputText.AppendLine("Date modified: " + basicProperties.DateModified); // Get extra properties List<string> propertiesName = new List<string>(); propertiesName.Add(dateAccessedProperty); propertiesName.Add(fileOwnerProperty); IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertiesName); var propValue = extraProperties[dateAccessedProperty]; if (propValue != null) { outputText.AppendLine("Date accessed: " + propValue); } propValue = extraProperties[fileOwnerProperty]; if (propValue != null) { outputText.AppendLine("File onwer: " + propValue); } OutputTextBlock.Text = outputText.ToString(); } } catch (FileNotFoundException) { //文件不存在 } }
6、Persisting access to storage item for future use :
使用这个 most-recently used (MRU) 列表去追踪用户频繁访问的项目(比如,文件、文件夹等)。这个 MRU 是由
windows 保持的,并且最多保持 25 项。
使用这个 future access list (FAL) 来访问应用程序没有指定的存储项目(比如,文件、文件夹等),例如,通过使用
file picker 访问。这个 FAL 最多保持 1000 项,并且必须由这个应用保存。
操作 :
为了添加一个列表,选择这个列表,然后单击 “Add to List”
为了浏览当前列表的内容,选择列表,然后单击 “Show List”
从列表中 打开 “sample.dat” 文件,选择列表然后单击 “Open from List”
操作截图:
操作结果:
(1)选中 Most Recently Used :
单击 “Add to List ” :
结果 :
单击 “Show List” :
结果 :
单击 “Open From List” :
结果 :
页面的 xaml :
<RadioButton x:Name="MRURadioButton" Content="Most Recently Used" GroupName="PersistenceList" IsChecked="True"/> <RadioButton x:Name="FALRadioButton" Content="Future Access List" GroupName="PersistenceList"/>
<Button x:Name="AddToListButton" Content="Add to List" Click="AddToListButton_Click"/> <Button x:Name="ShowListButton" Content="Show List" Click="ShowListButton_Click"/> <Button x:Name="OpenFromListButton" Content="Open from List" Click="OpenFromListButton_Click"/>
相应的按钮事件 :
Add To List :
public string mruToken = null; public string falToken = null; private void AddToListButton_Click(object sender, RoutedEventArgs e) { StorageFile file = sampleFile; if (file != null) { if (MRURadioButton.IsChecked.Value) { //MostRecentlyUsedList : 获取一个对象,该对象代表应用程序可用 //于跟踪应用程序最近访问过的文件和/或位置 (如文件夹) 的列表。 // 添加新的存储项并将元数据附在最近使用的 (MRU) 列表上。 mruToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Name); OutputTextBlock.Text = "The file '" + file.Name + "' was added to the MRU list and a token was stored."; } else if (FALRadioButton.IsChecked.Value) { falToken = StorageApplicationPermissions.FutureAccessList.Add(file, file.Name); OutputTextBlock.Text = "The file '" + file.Name + "' was added to the FAL list and a token was stored."; } } }
ShowListButton :
private void ShowListButton_Click(object sender, RoutedEventArgs e) { StorageFile file = sampleFile; if (file != null) { if (MRURadioButton.IsChecked.Value) { //AccessListEntryView : 位于应用程序的 StorageItemMostRecentlyUsedList 或 StorageItemAccessList 中的项的列表。 // 获取用于从最近使用的 (MRU) 列表中检索存储项的对象。 AccessListEntryView entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
if (entries.Count > 0) { StringBuilder outputText = new StringBuilder("The MRU list contains the following item(s):"
+ Environment.NewLine + Environment.NewLine); foreach (AccessListEntry entry in entries) { outputText.AppendLine(entry.Metadata); // Application previously chose to store file.Name in this field } OutputTextBlock.Text = outputText.ToString(); } else { OutputTextBlock.Text = "The MRU list is empty, please select 'Most Recently Used'
list and click 'Add to List' to add a file to the MRU list."; } } else if (FALRadioButton.IsChecked.Value) { // FutureAccessList : 获取一个对象,该对象代表应用程序维护的一个列表,该列表使应用程序可以存储文件和/或位置 (文件夹) 并在未来轻松地访问这些项。 AccessListEntryView entries = StorageApplicationPermissions.FutureAccessList.Entries;
if (entries.Count > 0) { StringBuilder outputText = new StringBuilder("The FAL list contains the following item(s):"
+ Environment.NewLine + Environment.NewLine); foreach (AccessListEntry entry in entries) { outputText.AppendLine(entry.Metadata); // Application previously chose to store file.Name in this field } OutputTextBlock.Text = outputText.ToString(); } else { OutputTextBlock.Text = "The FAL list is empty, please select 'Future Access List' list and
click 'Add to List' to add a file to the FAL list."; } } } }
OpenFromListButton:
private async void OpenFromListButton_Click(object sender, RoutedEventArgs e) { try { if (sampleFile != null) { if (MRURadioButton.IsChecked.Value) { if (rootPage.mruToken != null) { // Open the file via the token that was stored when adding this file into the MRU list //此方法成功完成时,它返回与指定的 token 关联的 storageFile。 StorageFile file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken); // Read the file string fileContent = await FileIO.ReadTextAsync(file); OutputTextBlock.Text = "The file '" + file.Name + "' was opened by a stored token from the MRU list
, it contains the following text:" + Environment.NewLine + Environment.NewLine + fileContent; } else { OutputTextBlock.Text = "The MRU list is empty, please select 'Most Recently Used' list and click 'Add to List' to
add a file to the MRU list."; } } else if (FALRadioButton.IsChecked.Value) { if (falToken != null) { // Open the file via the token that was stored when adding this file into the FAL list // 检索列表中的指定 StorageFile。 StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(falToken); // Read the file string fileContent = await FileIO.ReadTextAsync(file); OutputTextBlock.Text = "The file '" + file.Name + "' was opened by a stored token from the FAL list,
it contains the following text:" + Environment.NewLine + Environment.NewLine + fileContent; } else { OutputTextBlock.Text = "The FAL list is empty, please select 'Future Access List' list and click 'Add to List'
to add a file to the FAL list."; } } } } catch (FileNotFoundException) { //文件不存在 } }
7、Copying a file :
单击按钮,把 'sample.dat' 文件拷贝到 documents library 中。
<Button x:Name="CopyFileButton" Content="Copy" Click="CopyFileButton_Click"/>
private async void CopyFileButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { // 使用所需的名称,在指定文件夹中创建文件的副本。如果指定文件夹 //的现有文件已具有相同名称,则此方法还指定解决方法。 StorageFile fileCopy = await file.CopyAsync(KnownFolders.DocumentsLibrary, "sample - Copy.dat", NameCollisionOption.ReplaceExisting); OutputTextBlock.Text = "The file '" + file.Name + "' was copied and the new file was named '" + fileCopy.Name + "'."; } } catch (FileNotFoundException) { //文件不存在 } }
8、Deleting a file :
单击按钮,删除 'sample.dat' 文件。
<Button x:Name="DeleteFileButton" Content="Delete" Click="DeleteFileButton_Click"/>
private async void DeleteFileButton_Click(object sender, RoutedEventArgs e) { try { StorageFile file = sampleFile; if (file != null) { string filename = file.Name; // 删除当前文件。 await file.DeleteAsync(); sampleFile = null; OutputTextBlock.Text = "The file '" + filename + "' was deleted"; } } catch (FileNotFoundException) { //文件不存在 } }