程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> Windows 8開發入門(十二) windows 8的文件管理 1

Windows 8開發入門(十二) windows 8的文件管理 1

編輯:關於C#

File創建和String Stream Buffer方式讀寫

在本文中我們將學習Windows 8中的文件創建和多種讀寫方式以及設置文檔庫訪問權限和文件類型的訪問。

當然我們需要做以下准備工作:

首先:設置程序允許訪問的文件位置為:"庫\文檔",設置方法:點擊”Package.appxmanifest “,然後選擇”功能“選項卡,在功能列表中勾選”文檔庫訪問“。如下圖:

其次:設置程序允許以上文件夾內的文件類型,本實例中設置為txt後綴的文件:設置方法:點擊” Package.appxmanifest“,然後選擇”聲明“選項卡,在可用聲明下拉列表中選擇”文件類型關聯“,點擊” 添加“按鈕,並且在右邊的列表中添加”支持的文件類型為.txt,並且設置名稱為txt,當然你也可以繼續添 加允許訪問dat文件等,如下圖:

准備工作做好了,我們需要創建一個項目,然後寫入一下代碼進行訪問文件以及文件夾,創建文件和讀寫 文件。

Xaml代碼:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <!--顯示區-->
        <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="默認需要添加的文件內容" VerticalAlignment="Top" Width="431" Name="tbContent"/>
        <TextBlock HorizontalAlignment="Left" Margin="396,42,0,0" TextWrapping="Wrap" Text="文件內容:"
                   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"/>
        <!--創建文件以及普通string寫入讀取文本-->
        <Button Content="創建文件" 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數據" HorizontalAlignment="Left" Margin="127,173,0,0"
            x:Name="btnWriteBufferFile" VerticalAlignment="Top" Click="btnWriteBufferFile_Click" />
        <Button Content="讀取Buffer數據" HorizontalAlignment="Left" Margin="754,173,0,0"
            x:Name="btnReadBufferFile" VerticalAlignment="Top" Click="btnReadBufferFile_Click"/>
        <!--Stream方式寫入和讀取-->
        <Button Content="寫入Stream數據" HorizontalAlignment="Left" Margin="127,243,0,0"
            x:Name="btnWriteStreamFile" VerticalAlignment="Top" Click="btnWriteStreamFile_Click" 

/>
        <Button Content="讀取Stream數據" 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
    {
    
        public MainPage()
        {
            this.InitializeComponent();
        }
    
        /// <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)
        {
        }
    
        //獲取“庫\文檔”文件夾
        StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
    
        //創建文件以及普通string寫入讀取文本
        private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
        {

            StorageFile sf= await storageFolder.CreateFileAsync(this.tbFileName.Text.Trim(), 
                CreationCollisionOption.ReplaceExisting);
            tb_show.Text = "提示:創建了文件--" + this.tbFileName.Text.Trim();
        }
    
        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 = "提示:文件寫入成功,寫入內容為-“" + writestr + "”";
            }
            catch (Exception ex)
            {
                tb_show.Text = "提示:未找到該文件,請先創建文件";
            }
        }
    
        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方式讀取成功,讀取的內容為-“" + filecontent+"”

";
            }
            catch (Exception ex)
            {
                tb_show.Text = "提示:未找到該文件,請先創建文件";
            }
        }
        //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 = "提示:文件寫入成功,寫入內容為-“" + writestr + "”";
            }
            catch (Exception ex)
            {
                tb_show.Text = "提示:未找到該文件,請先創建文件";
            }
        }
    
        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方式讀取成功,讀取的內容為-“" + filecontent + "”";
            }
        }
    
        //將String轉為Buffer
        private IBuffer GetBufferFromString(String str)
        {
            using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
            {
                using (DataWriter dataWriter = new DataWriter(memoryStream))
                {
                    dataWriter.WriteString(str);
                    return dataWriter.DetachBuffer();
                }
            }
        }
    
        //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 = "提示:文件寫入成功,寫入內容為-“" + writestr + "”";
                    }
                }
            }
            catch (Exception ex)
            {
                tb_show.Text = "提示:未找到該文件,請先創建文件";
            }
               

        }
    
        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方式讀取成功,讀取的內容為-“" + filecontent + "”";
                    }
                }
            }
        }
    }

注意:由於創建文件和各種方式讀寫文件都是實用await關鍵字聲明,所以實用此代碼的方法名前必須 聲明為async關鍵字.

源碼下載:http://files.cnblogs.com/chengxingliang/Win8File.rar

VS2012+Windows8開發。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved