在本文中我們將學(xué)習(xí)Windows 8中的文件創(chuàng)建和多種讀寫方式以及設(shè)置文檔庫訪問權(quán)限和文件類型的訪問。
當(dāng)然我們需要做以下準(zhǔn)備工作:
首先:設(shè)置程序允許訪問的文件位置為:"庫\文檔",設(shè)置方法:點擊”Package.appxmanifest“,然后選擇”功能“選項卡,在功能列表中勾選”文檔庫訪問“。如下圖:
其次:設(shè)置程序允許以上文件夾內(nèi)的文件類型,本實例中設(shè)置為txt后綴的文件:設(shè)置方法:點擊”Package.appxmanifest“,然后選擇”聲明“選項卡,在可用聲明下拉列表中選擇”文件類型關(guān)聯(lián)“,點擊”添加“按鈕,并且在右邊的列表中添加”支持的文件類型為.txt,并且設(shè)置名稱為txt,當(dāng)然你也可以繼續(xù)添加允許訪問dat文件等,如下圖:
準(zhǔn)備工作做好了,我們需要創(chuàng)建一個項目,然后寫入一下代碼進(jìn)行訪問文件以及文件夾,創(chuàng)建文件和讀寫文件。
Xaml代碼:
Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
!--顯示區(qū)-->
TextBlock HorizontalAlignment="Left" Margin="137,42,0,0" TextWrapping="Wrap" Text="文件名:"
VerticalAlignment="Top" Height="23" Width="43"/>
TextBox HorizontalAlignment="Left" Margin="185,33,0,0" TextWrapping="Wrap"
Text="test.txt" VerticalAlignment="Top" Width="121" Name="tbFileName"/>
TextBox HorizontalAlignment="Left" Margin="457,33,0,0" TextWrapping="Wrap"
Text="默認(rèn)需要添加的文件內(nèi)容" VerticalAlignment="Top" Width="431" Name="tbContent"/>
TextBlock HorizontalAlignment="Left" Margin="396,42,0,0" TextWrapping="Wrap" Text="文件內(nèi)容:"
VerticalAlignment="Top" Height="23" Width="61"/>
TextBlock HorizontalAlignment="Left" Margin="127,317,0,0" TextWrapping="Wrap" Text="提示:"
VerticalAlignment="Top" Height="23" Width="761" Name="tb_show"/>
!--創(chuàng)建文件以及普通string寫入讀取文本-->
Button Content="創(chuàng)建文件" HorizontalAlignment="Left" Margin="127,99,0,0"
Name="btnCreateFile" VerticalAlignment="Top" Click="btnCreateFile_Click"/>
Button Content="寫入string文件" HorizontalAlignment="Left" Margin="430,99,0,0"
x:Name="btnWriteFile_Copy" VerticalAlignment="Top" Click="btnWriteFile_Copy_Click"/>
Button Content="讀取string文件" HorizontalAlignment="Left" Margin="757,99,0,0"
x:Name="btnReadFile" VerticalAlignment="Top" Click="btnReadFile_Click"/>
!--Buffer方式寫入和讀取-->
Button Content="寫入Buffer數(shù)據(jù)" HorizontalAlignment="Left" Margin="127,173,0,0"
x:Name="btnWriteBufferFile" VerticalAlignment="Top" Click="btnWriteBufferFile_Click" />
Button Content="讀取Buffer數(shù)據(jù)" HorizontalAlignment="Left" Margin="754,173,0,0"
x:Name="btnReadBufferFile" VerticalAlignment="Top" Click="btnReadBufferFile_Click"/>
!--Stream方式寫入和讀取-->
Button Content="寫入Stream數(shù)據(jù)" HorizontalAlignment="Left" Margin="127,243,0,0"
x:Name="btnWriteStreamFile" VerticalAlignment="Top" Click="btnWriteStreamFile_Click" />
Button Content="讀取Stream數(shù)據(jù)" HorizontalAlignment="Left" Margin="748,243,0,0"
x:Name="btnReadStreamFile" VerticalAlignment="Top" Click="btnReadStreamFile_Click"/>
/Grid>
cs代碼:
/// summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// /summary>
public sealed partial class MainPage : Page
{/p>
p> public MainPage()
{
this.InitializeComponent();
}/p>
p> /// summary>
/// Invoked when this page is about to be displayed in a Frame.
/// /summary>
/// param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page./param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}/p>
p> //獲取“庫\文檔”文件夾
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;/p>
p> //創(chuàng)建文件以及普通string寫入讀取文本
private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
{
StorageFile sf= await storageFolder.CreateFileAsync(this.tbFileName.Text.Trim(),
CreationCollisionOption.ReplaceExisting);
tb_show.Text = "提示:創(chuàng)建了文件--" + this.tbFileName.Text.Trim();
}/p>
p> private async void btnWriteFile_Copy_Click(object sender, RoutedEventArgs e)
{
try
{
string writestr = this.tbContent.Text.Trim() + "text方式";
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
await FileIO.WriteTextAsync(sf, writestr);
tb_show.Text = "提示:文件寫入成功,寫入內(nèi)容為-“" + writestr + "”";
}
catch (Exception ex)
{
tb_show.Text = "提示:未找到該文件,請先創(chuàng)建文件";
}
}/p>
p> private async void btnReadFile_Click(object sender, RoutedEventArgs e)
{
try
{
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
string filecontent= await FileIO.ReadTextAsync(sf,UnicodeEncoding.Utf8);
tb_show.Text = "提示:文件以string方式讀取成功,讀取的內(nèi)容為-“" + filecontent+"”";
}
catch (Exception ex)
{
tb_show.Text = "提示:未找到該文件,請先創(chuàng)建文件";
}
}
//Buffer方式寫入和讀取
private async void btnWriteBufferFile_Click(object sender, RoutedEventArgs e)
{
try
{
string writestr = this.tbContent.Text.Trim() + "buffer方式";
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
IBuffer buffer = GetBufferFromString(writestr);
await FileIO.WriteBufferAsync(sf, buffer);
tb_show.Text = "提示:文件寫入成功,寫入內(nèi)容為-“" + writestr + "”";
}
catch (Exception ex)
{
tb_show.Text = "提示:未找到該文件,請先創(chuàng)建文件";
}
}/p>
p> private async void btnReadBufferFile_Click(object sender, RoutedEventArgs e)
{
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
IBuffer buffer = await FileIO.ReadBufferAsync(sf);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
string filecontent = dataReader.ReadString(buffer.Length);
tb_show.Text = "提示:文件以Buffer方式讀取成功,讀取的內(nèi)容為-“" + filecontent + "”";
}
}/p>
p> //將String轉(zhuǎn)為Buffer
private IBuffer GetBufferFromString(String str)
{
using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
{
using (DataWriter dataWriter = new DataWriter(memoryStream))
{
dataWriter.WriteString(str);
return dataWriter.DetachBuffer();
}
}
}/p>
p> //Stream方式寫入和讀取
private async void btnWriteStreamFile_Click(object sender, RoutedEventArgs e)
{
try
{
string writestr = this.tbContent.Text.Trim() + "Stream方式";
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
using (StorageStreamTransaction transaction = await sf.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
dataWriter.WriteString(writestr);
transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
await transaction.CommitAsync();
tb_show.Text = "提示:文件寫入成功,寫入內(nèi)容為-“" + writestr + "”";
}
}
}
catch (Exception ex)
{
tb_show.Text = "提示:未找到該文件,請先創(chuàng)建文件";
}
}/p>
p> private async void btnReadStreamFile_Click(object sender, RoutedEventArgs e)
{
StorageFile sf = await storageFolder.GetFileAsync(this.tbFileName.Text.Trim());
using (IRandomAccessStream readStream = await sf.OpenAsync(FileAccessMode.Read))
{
using (DataReader dataReader = new DataReader(readStream))
{
UInt64 size = readStream.Size;
if (size = UInt32.MaxValue)
{
UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
string filecontent = dataReader.ReadString(numBytesLoaded);
tb_show.Text = "提示:文件以Stream方式讀取成功,讀取的內(nèi)容為-“" + filecontent + "”";
}
}
}
}
}
如需源碼請點擊 Win8File_jb51net.rar 下載。VS2012+Windows8開發(fā)。