Windows 8实用窍门系列:12.windows 8的文件管理---1.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关键字.

  如需源码请点击 Win8File.rar 下载。VS2012+Windows8开发。


本文转自程兴亮博客园博客,原文链接:http://www.cnblogs.com/chengxingliang/archive/2012/12/17/2819568.html,如需转载请自行联系原作者

相关文章
|
12月前
|
Windows
Windows常见可读写目录的探测
Windows常见可读写目录的探测
140 0
Windows常见可读写目录的探测
|
3月前
InputStream,String,File相互转化
InputStream,String,File相互转化
21 3
|
17天前
|
API C# Shell
WPF与Windows Shell完美融合:深入解析文件系统操作技巧——从基本文件管理到高级Shell功能调用,全面掌握WPF中的文件处理艺术
【8月更文挑战第31天】Windows Presentation Foundation (WPF) 是 .NET Framework 的关键组件,用于构建 Windows 桌面应用程序。WPF 提供了丰富的功能来创建美观且功能强大的用户界面。本文通过问题解答的形式,探讨了如何在 WPF 应用中集成 Windows Shell 功能,并通过具体示例代码展示了文件系统的操作方法,包括列出目录下的所有文件、创建和删除文件、移动和复制文件以及打开文件夹或文件等。
32 0
|
24天前
|
存储 Linux Windows
【应用服务 App Service】App Service For Windows 如何挂载Storage Account File Share 示例
【应用服务 App Service】App Service For Windows 如何挂载Storage Account File Share 示例
|
26天前
|
Linux Python Windows
【Azure 环境】Windows中安装Python azure-eventhub-checkpointstoreblob-aio模块时出错 ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory:
【Azure 环境】Windows中安装Python azure-eventhub-checkpointstoreblob-aio模块时出错 ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory:
|
4月前
|
存储 文件存储 数据安全/隐私保护
Windows部署开源文件管理器File Browser并实现远程访问本地文件
Windows部署开源文件管理器File Browser并实现远程访问本地文件
161 1
|
9月前
|
存储 安全 数据安全/隐私保护
3.2 Windows驱动开发:内核CR3切换读写内存
CR3是一种控制寄存器,它是CPU中的一个专用寄存器,用于存储当前进程的页目录表的物理地址。在x86体系结构中,虚拟地址的翻译过程需要借助页表来完成。页表是由页目录表和页表组成的,页目录表存储了页表的物理地址,而页表存储了实际的物理页框地址。因此,页目录表的物理地址是虚拟地址翻译的关键之一。在操作系统中,每个进程都有自己的地址空间,地址空间中包含了进程的代码、数据和堆栈等信息。为了实现进程间的隔离和保护,操作系统会为每个进程分配独立的地址空间。在这个过程中,操作系统会将每个进程的页目录表的物理地址存储在它自己的CR3寄存器中。当进程切换时,操作系统会修改CR3寄存器的值,从而让CPU使用新的页
152 0
3.2 Windows驱动开发:内核CR3切换读写内存
|
10月前
|
安全 Windows
3.3 Windows驱动开发:内核MDL读写进程内存
MDL内存读写是一种通过创建MDL结构体来实现跨进程内存读写的方式。在Windows操作系统中,每个进程都有自己独立的虚拟地址空间,不同进程之间的内存空间是隔离的。因此,要在一个进程中读取或写入另一个进程的内存数据,需要先将目标进程的物理内存映射到当前进程的虚拟地址空间中,然后才能进行内存读写操作。
79 0
3.3 Windows驱动开发:内核MDL读写进程内存
|
4月前
记录以下出现:java.io.IOException: (null) entry in command string: null ls -F E:\file\a.txt 情况怎么办?
记录以下出现:java.io.IOException: (null) entry in command string: null ls -F E:\file\a.txt 情况怎么办?
113 0
|
存储 安全 数据安全/隐私保护
Windows7文件与文件管理
2.3Windows 7的文件和文件夹管理 2.3.1文件和文件夹的概念 存放在计算机中的所有程序以及各种类型的数据,都是以文件的形式存储在磁盘上的,因此文件的组织和管理师操作系统要完成的主要功能之一。 在Windows 7中,可以使用“计算机”和“Windows资源管理器”来完成对文件、文件夹后果其他资源的管理。 所谓文件(File),是指存放在外存储器上的一组相关信息的集合。每个文件都有一个名字,称为文件名。文件名是操作系统中区分不同文件的唯一标志。 文件名是操作系统中区分不同文件的唯一标志,同一文件夹下,文件与文件不能重名,文件与文件夹不能重名,文件夹与文件夹不能重名。 文件名