文件系統: 文本的讀寫, 二進制的讀寫, 流的讀寫, 最近訪問列表和未來訪問列表
介紹
重新想象 Windows 8 Store Apps 之 文件系統
演示如何讀寫文本數據
演示如何讀寫二進制數據
演示如何讀寫流數據
演示如何讀寫“最近訪問列表”和“未來訪問列表”
示例
1、演示如何讀寫文本數據
FileSystem/ReadWriteText.xaml.cs
/*
* 演示如何讀寫文本數據
* 注:如果需要讀寫某擴展名的文件,需要在 Package.appxmanifest 增加“文件類型關聯”聲明,並做相
應的配置
*
* StorageFolder - 文件夾操作類
* 獲取文件夾相關屬性、重命名、Create...、Get...等
*
* StorageFile - 文件操作類
* 獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
*
* FileIO - 用於讀寫 IStorageFile 對象的幫助類
* WriteTextAsync() - 將指定的文本數據寫入到指定的文件
* AppendTextAsync() - 將指定的文本數據追加到指定的文件
* WriteLinesAsync() - 將指定的多行文本數據寫入到指定的文件
* AppendLinesAsync() - 將指定的多行文本數據追加到指定的文件
* ReadTextAsync() - 獲取指定的文件中的文本數據
* ReadLinesAsync() - 獲取指定的文件中的文本數據,返回的是一行一行的數據
*
* 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
*/
using System;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace XamlDemo.FileSystem
{
public sealed partial class ReadWriteText : Page
{
public ReadWriteText()
{
this.InitializeComponent();
}
private async void btnWriteText_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下創建指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdText.txt", CreationCollisionOption.ReplaceExisting);
// 在指定的文件中寫入指定的文本
string textContent = "I am webabcd";
await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);
lblMsg.Text = "寫入成功";
}
private async void btnReadText_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下獲取指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdText.txt");
if (storageFile != null)
{
// 獲取指定的文件中的文本內容
string textContent = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
lblMsg.Text = "讀取結果:" + textContent;
}
}
}
}
2、演示如何讀寫二進制數據
FileSystem/ReadWriteBinary.xaml.cs
/*
* 演示如何讀寫二進制數據
* 注:如果需要讀寫某擴展名的文件,需要在 Package.appxmanifest 增加“文件類型關聯”聲明,並做相應的配置
*
* StorageFolder - 文件夾操作類
* 獲取文件夾相關屬性、重命名、Create...、Get...等
*
* StorageFile - 文件操作類
* 獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
*
* FileIO - 用於讀寫 IStorageFile 對象的幫助類
* WriteBufferAsync() - 將指定的二進制數據寫入指定的文件
* ReadBufferAsync() - 獲取指定的文件中的二進制數據
*
* IBuffer - WinRT 中的字節數組
*
* 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
*/
using System;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace XamlDemo.FileSystem
{
public sealed partial class ReadWriteBinary : Page
{
public ReadWriteBinary()
{
this.InitializeComponent();
}
private async void btnWriteBinary_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下創建指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdBinary.txt", CreationCollisionOption.ReplaceExisting);
// 將字符串轉換成二進制數據,並保存到指定文件
string textContent = "I am webabcd";
IBuffer buffer = ConverterHelper.String2Buffer(textContent);
await FileIO.WriteBufferAsync(storageFile, buffer);
lblMsg.Text = "寫入成功";
}
private async void btnReadBinary_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下獲取指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdBinary.txt");
if (storageFile != null)
{
// 獲取指定文件中的二進制數據,將其轉換成字符串並顯示
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
string textContent = ConverterHelper.Buffer2String(buffer);
lblMsg.Text = "讀取結果:" + textContent;
}
}
}
}
3、演示如何讀寫流數據
FileSystem/ReadWriteStream.xaml.cs
/*
* 演示如何讀寫流數據
* 注:如果需要讀寫某擴展名的文件,需要在 Package.appxmanifest 增加“文件類型關聯”聲明,並做相應的配置
*
* StorageFolder - 文件夾操作類
* 獲取文件夾相關屬性、重命名、Create...、Get...等
*
* StorageFile - 文件操作類
* 獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
*
* IBuffer - WinRT 中的字節數組
*
* IInputStream - 需要讀取的流
* IOutputStream - 需要寫入的流
* IRandomAccessStream - 需要讀取、寫入的流,其繼承自 IInputStream 和 IOutputStream
*
* DataReader - 從數據流中讀取數據,即從 IInputStream 讀取
* LoadAsync() - 從數據流中加載指定長度的數據到緩沖區
* ReadInt32(), ReadByte(), ReadString() 等 - 從緩沖區中讀取數據
* DataWriter - 將數據寫入數據流,即寫入 IOutputStream
* WriteInt32(), WriteByte(), WriteString() 等 - 將數據寫入緩沖區
* StoreAsync() - 將緩沖區中的數據保存到數據流
*
* StorageStreamTransaction - 用於寫數據流到文件的類(具體用法,詳見下面的代碼)
* Stream - 數據流(只讀)
* CommitAsync - 將數據流保存到文件
*
* 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
*/
using System;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace XamlDemo.FileSystem
{
public sealed partial class ReadWriteStream : Page
{
public ReadWriteStream()
{
this.InitializeComponent();
}
private async void btnWriteStream_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下創建指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting);
string textContent = "I am webabcd";
using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
// 將字符串寫入數據流,然後將數據流保存到文件
dataWriter.WriteString(textContent);
transaction.Stream.Size = await dataWriter.StoreAsync();
await transaction.CommitAsync();
lblMsg.Text = "寫入成功";
}
}
}
private async void btnReadStream_Click_1(object sender, RoutedEventArgs e)
{
// 在指定的目錄下獲取指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdStream.txt");
if (storageFile != null)
{
using (IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.Read))
{
using (DataReader dataReader = new DataReader(randomStream))
{
ulong size = randomStream.Size;
if (size <= uint.MaxValue)
{
// 獲取數據流,從中讀取字符串值並顯示
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
string fileContent = dataReader.ReadString(numBytesLoaded);
lblMsg.Text = "讀取結果:" + fileContent;
}
}
}
}
}
}
}
4、演示如何讀寫“最近訪問列表”和“未來訪問列表”
FileSystem/CacheAccess.xaml
<Page
x:Class="XamlDemo.FileSystem.CacheAccess"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.FileSystem"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="Transparent">
<StackPanel Margin="120 0 0 0">
<TextBlock Name="lblMsg" FontSize="14.667" />
<Button Name="btnAddToMostRecentlyUsedList" Content="AddToMostRecentlyUsedList" Click="btnAddToMostRecentlyUsedList_Click_1" Margin="0 10 0 0" />
<Button Name="btnGetMostRecentlyUsedList" Content="GetMostRecentlyUsedList" Click="btnGetMostRecentlyUsedList_Click_1" Margin="0 10 0 0" />
<Button Name="btnAddToFutureAccessList" Content="AddToFutureAccessList" Click="btnAddToFutureAccessList_Click_1" Margin="0 10 0 0" />
<Button Name="btnGetFutureAccessList" Content="GetFutureAccessList" Click="btnGetFutureAccessList_Click_1" Margin="0 10 0 0" />
</StackPanel>
</Grid>
</Page>
FileSystem/CacheAccess.xaml.cs
/*
* 演示如何讀寫“最近訪問列表”和“未來訪問列表”
* 注:如果需要讀寫某擴展名的文件,需要在 Package.appxmanifest 增加“文件類型關聯”聲明,並做相應的配置
*
* StorageFolder - 文件夾操作類
* 獲取文件夾相關屬性、重命名、Create...、Get...等
*
* StorageFile - 文件操作類
* 獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、Replace...等
*
* StorageApplicationPermissions - 文件/文件夾的訪問列表
* MostRecentlyUsedList - 最近訪問列表(實現了 IStorageItemAccessList 接口)
* Add(IStorageItem file, string metadata) - 添加文件或文件夾到“最近訪問列表”,返回 token 值(一個字符串類型的標識),通過此值可以方便地檢索到對應的文件或文件夾
* file - 需要添加到列表的文件或文件夾
* metadata - 自定義元數據,相當於上下文
* AddOrReplace(string token, IStorageItem file, string metadata) - 添加文件或文件夾到“最近訪問列表”,如果已存在則替換
* GetFileAsync(string token) - 根據 token 值,在“最近訪問列表”查找對應的文件
* GetFolderAsync(string token) - 根據 token 值,在“最近訪問列表”查找對應的文件夾
* GetItemAsync(string token) - 根據 token 值,在“最近訪問列表”查找對應的文件或文件夾
* Entries - 返回 AccessListEntryView 類型的數據,其是 AccessListEntry 類型數據的集合
* FutureAccessList - 未來訪問列表(實現了 IStorageItemAccessList 接口)
* 基本用法同“MostRecentlyUsedList”
*
* AccessListEntry - 用於封裝訪問列表中的 StorageFile 或 StorageFolder 的 token 和元數據
* Token - token 值
* Metadata - 元數據
*
* 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
*/
using System;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace XamlDemo.FileSystem
{
public sealed partial class CacheAccess : Page
{
public CacheAccess()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// 在指定的目錄下創建指定的文件
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdCacheAccess.txt", CreationCollisionOption.ReplaceExisting);
// 在指定的文件中寫入指定的文本
string textContent = "I am webabcd";
await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);
}
private async void btnAddToMostRecentlyUsedList_Click_1(object sender, RoutedEventArgs e)
{
// 獲取文件對象
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdCacheAccess.txt");
if (storageFile != null)
{
// 將文件添加到“最近訪問列表”,並獲取對應的 token 值
string token = StorageApplicationPermissions.MostRecentlyUsedList.Add(storageFile, storageFile.Name);
lblMsg.Text = "token:" + token;
}
}
private async void btnAddToFutureAccessList_Click_1(object sender, RoutedEventArgs e)
{
// 獲取文件對象
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdCacheAccess.txt");
if (storageFile != null)
{
// 將文件添加到“未來訪問列表”,並獲取對應的 token 值
string token = StorageApplicationPermissions.FutureAccessList.Add(storageFile, storageFile.Name);
lblMsg.Text = "token:" + token;
}
}
private async void btnGetMostRecentlyUsedList_Click_1(object sender, RoutedEventArgs e)
{
AccessListEntryView entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
if (entries.Count > 0)
{
// 通過 token 值,從“最近訪問列表”中獲取文件對象
AccessListEntry entry = entries[0];
StorageFile storageFile = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(entry.Token);
string textContent = await FileIO.ReadTextAsync(storageFile);
lblMsg.Text = "MostRecentlyUsedList 的第一個文件的文本內容:" + textContent;
}
else
{
lblMsg.Text = "最近訪問列表中無數據";
}
}
private async void btnGetFutureAccessList_Click_1(object sender, RoutedEventArgs e)
{
AccessListEntryView entries = StorageApplicationPermissions.FutureAccessList.Entries;
if (entries.Count > 0)
{
// 通過 token 值,從“未來訪問列表”中獲取文件對象
AccessListEntry entry = entries[0];
StorageFile storageFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(entry.Token);
string textContent = await FileIO.ReadTextAsync(storageFile);
lblMsg.Text = "FutureAccessList 的第一個文件的文本內容:" + textContent;
}
else
{
lblMsg.Text = "未來訪問列表中無數據";
}
}
}
}
OK
[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar