图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件

我们紧接着上篇,这篇将介绍如何使用文件选择器选择您的应用程序文件和文件夹,
根据用户指定的名称,文件类型和文件保存的位置。

-----------------------------------我是华丽的分割线-----------------------------------------
今天我们要用Windows Runtime API中的的Windows.Storage和Windows.Storage.AccessCache来
演示如何创建,读,写,复制和删除文件,如何检索文件的属性,
以及如何使应用程序记住最近访问的文件或文件夹,以便以后可以访问它。

本篇将介绍如下八个方面:

  a)在文档库中创建一个文件
  b)在一个文件中写入和读取文本
  c)在一个文件中写入和读取字节
  d)读和写文件使用流的方式
  e)显示文件的属性
  f)记住一个文件或文件夹,以便您可以稍后访问(持续访问)
  g)复制一个文件
  h)删除一个文件

我们的创建的步骤如下:
1)为了组织文件方便,我们先建一个文件夹FileAccess
2)向文件夹中添加如下八个文件:  

  CreatingAFile.xaml,WritingAndReadingText.xaml,WritingAndReadingBytes.xaml,
  WritingAndReadingUsingStream.xaml,DisplayingFileProperties.xaml,
  PersistingAccess.xaml,CopyAFile.xaml,DeleteAFile.xaml

  创建方法请参照前一篇.

3)此时的解决方案结构如下: 

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第1张图片

4)向我们的DataSource添加导航所需要的信息

  修改我们的SampleDataSource.cs文件中的SampleDataSource类中的代码,

  代码如下: 

View Code
        public SampleDataSource()
        {
            #region Group1
            var group1 = new SampleDataGroup("FilePicker",
              "Use Windows.Storage.Pickers API",
              "Access and save files using the file picker",
              "Assets/FilePicker.jpg",
              "");
            group1.Items.Add(new SampleDataItem("FilePicker-PickASinglePhoto",
                    "Pick a single photo",
                    "only one file can selected,file type is jpg,jpeg,png",
                    "Assets/FilePicker.jpg",
                    "only one file can selected ",
                    "",
                    group1,
                    typeof(PickASinglePhoto)));
            group1.Items.Add(new SampleDataItem("FilePicker-PickMultipleFiles",
                    "Pick multiple files",
                    "you can pick multiple files",
                    "Assets/FilePicker.jpg",
                    "pick multiple files",
                    "",
                    group1,
                    typeof(PickMultipleFiles)));
            group1.Items.Add(new SampleDataItem("FilePicker-PickAFolder",
                    "Pick a folder",
                    "you can pick a folder",
                    "Assets/FilePicker.jpg",
                    "Pick a folder",
                    "",
                    group1,
                    typeof(PickAFolder)));
            group1.Items.Add(new SampleDataItem("FilePicker-SaveAFile",
                    "Save a file",
                    "you can save a file",
                    "Assets/FilePicker.jpg",
                    "Save a file",
                    "",
                    group1,
                    typeof(SaveAFile)));
            this.AllGroups.Add(group1);
            #endregion

            #region Group2
            var group2 = new SampleDataGroup("FileAceess",
           "Using Windows.Storage API",
           "File access",
           "Assets/FileAccess.jpg",
           "");
            group2.Items.Add(new SampleDataItem("FileAceess-CreatingAFile",
                    "Create a file",
                    "Using CreateFileAsync Create a file",
                    "Assets/FileAccess.jpg",
                    "Using CreateFileAsync",
                    "",
                    group2,
                    typeof(CreatingAFile)));

            group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingText",
               "Write And Read A Text",
               "Using WriteTextAsync,ReadTextAsync Write And Read  Text",
               "Assets/FileAccess.jpg",
               "Using WriteTextAsync,ReadTextAsync",
               "",
               group2,
               typeof(WritingAndReadingText)));

            group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingBytes",
              "Writing and reading bytes in a file",
              "Using WriteBufferAsync,ReadBufferAsync Write And Read bytes",
              "Assets/FileAccess.jpg",
              "Using WriteBufferAsync,ReadBufferAsync",
              "",
              group2,
              typeof(WritingAndReadingBytes)));

            group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingUsingStream",
                "Writing and reading using a stream",
                "Using OpenAsync Writing and reading using a stream",
                "Assets/FileAccess.jpg",
                "Using OpenAsync",
                "",
                group2,
                typeof(WritingAndReadingUsingStream)));

            group2.Items.Add(new SampleDataItem("FileAceess-DisplayingFileProperties",
                "Displaying file properties",
                "Using GetBasicPropertiesAsync  Get File Properties",
                "Assets/FileAccess.jpg",
                "Using GetBasicPropertiesAsync",
                "",
                group2,
                typeof(DisplayingFileProperties)));

            group2.Items.Add(new SampleDataItem("FileAceess-PersistingAccess",
                "Persisting access to a storage item for future use",
                "Using MostRecentlyUsedList",
                "Assets/FileAccess.jpg",
                "Using MostRecentlyUsedList",
                "",
                group2,
                typeof(PersistingAccess)));

            group2.Items.Add(new SampleDataItem("FileAceess-CopyAFile",
                "Copy a file",
                "Using CopyAsync Copy a file",
                "Assets/FileAccess.jpg",
                "Using CopyAsync",
                "",
                group2,
                typeof(CopyAFile)));

            group2.Items.Add(new SampleDataItem("FileAceess-DeleteAFile",
                "Delete a file",
                "Using DeleteAsync Delete a file",
                "Assets/FileAccess.jpg",
                "Using DeleteAsync",
                "",
                group2,
                typeof(DeleteAFile)));

            this.AllGroups.Add(group2);
            #endregion
        }

 

 

5)我们的导航这样就做好了,效果图:

点击,出现如下图片:

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第2张图片

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第3张图片

6)在文档库中创建一个文件

  使用StorageFolder的CreateFileAsync方法来创建该文件。

  修改我们的CreatingAFile.xaml的xaml代码:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                Create a new file 'Refact's Blog.refactor'  in the document library.
            </TextBlock>

            <Button Grid.Row="1" x:Name="CreateFileButton" Content="Create File" Margin="0,0,10,0"/>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
   public sealed partial class CreatingAFile : Page
    {
        FileAccess acc = new FileAccess();

        public CreatingAFile()
        {
            this.InitializeComponent();
            CreateFileButton.Click += new RoutedEventHandler(CreateFileButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text=acc.ValidateFile(this.GetType());
        }

        /// <summary>
        /// Creates a new file
        /// </summary>
        private async void CreateFileButton_Click(object sender, RoutedEventArgs e)
        {
            //获取文档库
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            acc.sampleFile = await storageFolder.CreateFileAsync(FileAccess.FILENAME, CreationCollisionOption.ReplaceExisting);
            OutputTextBlock.Text = "The file '" + acc.sampleFile.Name + "' was created.";
        }
    }

 

  为了方便在其它页面操作,我们新建一个类:FileAccess

View Code
   public class FileAccess
    {
       /// <summary>
       /// 创建的文件名
       /// </summary>
       public const string FILENAME = "Refact's Blog.refactor";

       public StorageFile sampleFile = null;

       /// <summary>
       /// 检查文件是不是存在
       /// </summary>
       public async void Initialize()
       {
           try
           {
               sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(FILENAME);
           }
           catch (FileNotFoundException)
           {
               
           }
       }

       public string ValidateFile(Type classType)
       {
           if (classType != typeof(CreatingAFile) && sampleFile == null)
           {
               return "文件名为" + FILENAME + "文件不存在,请先运行CreatingAFile";
           }
           return "";
       }
    }

 

  效果图,不再提供.如需要,请在评论中说明!

7)我们的程序需要文档库的权限,所以我们要更改Package.appxmanifest,如图:

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第4张图片

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第5张图片

8)在一个文件中写入和读取文本

  使用文件IO的WriteTextAsync和文件IO的ReadTextAsync方法来读写文件。

  修改我们的WritingAndReadingText.xaml的xaml:

View Code
  <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                To write some text to 'Refact's Blog.refactor', type something in the textbox below and click 'Write'.
                To read the contents of 'Refact's Blog.refactor', click 'Read'.
            </TextBlock>

            <StackPanel Grid.Row="1" Orientation="Vertical">
                <TextBox x:Name="InputTextBox" IsReadOnly="false" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/>
                <StackPanel Orientation="Horizontal" Margin="10,10,10,10">
                    <Button x:Name="WriteTextButton" Content="Write" Margin="0,0,10,0"/>
                    <Button x:Name="ReadTextButton" Content="Read" Margin="0,0,10,0"/>
                </StackPanel>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class WritingAndReadingText : Page
    {
        FileAccess acc = new FileAccess();
        public WritingAndReadingText()
        {
            this.InitializeComponent();
            WriteTextButton.Click += new RoutedEventHandler(WriteTextButton_Click);
            ReadTextButton.Click += new RoutedEventHandler(ReadTextButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                WriteTextButton.IsEnabled = false;
                ReadTextButton.IsEnabled = false;
            }
        }

        private async void WriteTextButton_Click(object sender, RoutedEventArgs e)
        {
            //获得文件
            StorageFile file = acc.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.";
                }
            }
        }

        private async void ReadTextButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.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;
            }
        }
    }

 

9)在一个文件中写入和读取字节

  使用文件IO的WriteBufferAsync和文件IO的ReadBufferAsync方法来读写文件。

  修改我们的WritingAndReadingBytes.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                To write some set of bytes to 'Refact's Blog.refactor', type something in the textbox below and click 'Write'.
                To read a set of bytes with the contents of 'Refact's Blog.refactor', click 'Read'.
            </TextBlock>

            <StackPanel Grid.Row="1" Orientation="Vertical">
                <TextBox x:Name="InputTextBox" IsReadOnly="false" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/>
                <StackPanel Orientation="Horizontal">
                    <Button x:Name="WriteBytesButton" Content="Write" Margin="0,0,10,0"/>
                    <Button x:Name="ReadBytesButton" Content="Read" Margin="0,0,10,0"/>
                </StackPanel>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class WritingAndReadingBytes : Page
    {
        FileAccess acc = new FileAccess();
        public WritingAndReadingBytes()
        {
            this.InitializeComponent();
            WriteBytesButton.Click += new RoutedEventHandler(WriteBytesButton_Click);
            ReadBytesButton.Click += new RoutedEventHandler(ReadBytesButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                WriteBytesButton.IsEnabled = false;
                ReadBytesButton.IsEnabled = false;
            }
        }

        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 WriteBytesButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.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;
                }
                else
                {
                    OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again.";
                }
            }
        }

        private async void ReadBytesButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.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;
                }
            }
        }
    }

 

10)读和写文件使用流的方式

  使用StorageFile的OpenAsync方法,DataWriter类和DataReader类

  修改我们的WritingAndReadingUsingStream.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                To write some text to 'Refact's Blog.refactor' using a stream, type something in the textbox below and click 'Write'.
                To read the contents of 'Refact's Blog.refactor' using a stream, click 'Read'.
            </TextBlock>

            <StackPanel Grid.Row="1" Orientation="Vertical">
                <TextBox x:Name="InputTextBox" IsReadOnly="false" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/>
                <StackPanel Orientation="Horizontal">
                    <Button x:Name="WriteToStreamButton" Content="Write" Margin="0,0,10,0"/>
                    <Button x:Name="ReadFromStreamButton" Content="Read" Margin="0,0,10,0"/>
                </StackPanel>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class WritingAndReadingUsingStream : Page
    {
        FileAccess acc = new FileAccess();
        public WritingAndReadingUsingStream()
        {
            this.InitializeComponent();
            WriteToStreamButton.Click += new RoutedEventHandler(WriteToStreamButton_Click);
            ReadFromStreamButton.Click += new RoutedEventHandler(ReadFromStreamButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                WriteToStreamButton.IsEnabled = false;
                ReadFromStreamButton.IsEnabled = false;
            }
        }

        private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e)
        {
            //获得文件
            StorageFile file = acc.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(); 
                            //提交
                            await transaction.CommitAsync();
                            OutputTextBlock.Text = "The following text was written to '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + userContent;
                        }
                    }
                }
                else
                {
                    OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again.";
                }
            }
        }

        private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                //随机访问输入输出流中的数据
                using (IRandomAccessStream readStream = await file.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);
                            OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + 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.";
                        }
                    }
                }
            }
        }
    }

 

11)显示文件的属性

  使用的StorageFile的GetBasicPropertiesAsync方法和的StorageFile的Properties的属性,

  以获得该文件的属性。

  修改我们的DisplayingFileProperties.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                To retrieve and display file properties for 'Refact's Blog.refactor', click 'Show Properties'.
            </TextBlock>

            <Button Grid.Row="1" x:Name="ShowPropertiesButton" Content="Show Properties" Margin="0,0,10,0"/>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class DisplayingFileProperties : Page
    {
        FileAccess acc = new FileAccess();
        static readonly string dateAccessedProperty = "System.DateAccessed";
        static readonly string fileOwnerProperty = "System.FileOwner";

        public DisplayingFileProperties()
        {
            this.InitializeComponent();
            ShowPropertiesButton.Click += new RoutedEventHandler(ShowPropertiesButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                ShowPropertiesButton.IsEnabled = false;
            }
        }

        private async void ShowPropertiesButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                StringBuilder outputText = new StringBuilder();
                outputText.AppendLine("File name: " + file.Name);
                outputText.AppendLine("File type: " + file.FileType);

                //对基本属性的访问
                BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
                outputText.AppendLine("File size: " + basicProperties.Size + " bytes");
                outputText.AppendLine("Date modified: " + basicProperties.DateModified);

                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();
            }
        }
    }

 

12)记住一个文件或文件夹,以便您可以稍后访问(持续访问)

  使用的StorageApplicationPermissions的FutureAccessList
  和StorageApplicationPermissions的MostRecentlyUsedList性能要记住一个文件或文件夹,以便以后可以访问它。

  修改我们的PersistingAccess.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                Use the most-recently used (MRU) list to track storage items (like files, folders, etc.) that the user accesses frequently.
                The MRU holds up to 25 items and is maintained by Windows.
                <LineBreak/><LineBreak/>
                Use the future access list (FAL) to preserve access to storage items (like files, folders, etc.) in locations that are not specified by
                the app's capabilities, like items that are accessed through the file picker. The FAL holds up to 1000 items and must be maintained by the app.
                <LineBreak/><LineBreak/>
                To add to a list, select the list and then click 'Add to List'.
                To view the current contents of a list, select the list and then click 'Show List'.
                To open 'sample.dat' from a list, select the list and then click 'Open from List'.
            </TextBlock>

            <StackPanel Grid.Row="1" Orientation="Vertical">
                <RadioButton x:Name="MRURadioButton" Content="Most Recently Used" HorizontalAlignment="Left" GroupName="PersistenceList" IsChecked="True"/>
                <RadioButton x:Name="FALRadioButton" Content="Future Access List" HorizontalAlignment="Left" GroupName="PersistenceList"/>
            </StackPanel>

            <StackPanel Grid.Row="2" Orientation="Horizontal">
                <Button x:Name="AddToListButton" Content="Add to List" Margin="0,0,10,0"/>
                <Button x:Name="ShowListButton" Content="Show List" Margin="0,0,10,0"/>
                <Button x:Name="OpenFromListButton" Content="Open from List" Margin="0,0,10,0"/>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class PersistingAccess : Page
    {
        FileAccess acc = new FileAccess();
        public string mruToken = null;
        public string falToken = null;

        public PersistingAccess()
        {
            this.InitializeComponent();
            AddToListButton.Click += new RoutedEventHandler(AddToListButton_Click);
            ShowListButton.Click += new RoutedEventHandler(ShowListButton_Click);
            OpenFromListButton.Click += new RoutedEventHandler(OpenFromListButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                AddToListButton.IsEnabled = false;
                ShowListButton.IsEnabled = false;
                OpenFromListButton.IsEnabled = false;
            }
        }

        private void AddToListButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                if (MRURadioButton.IsChecked.Value)
                {
                    //将文件的元数据项添加到最近使用的列表上
                    this.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)
                {
                    //将文件的元数据项添加到访问列表上
                    this.falToken = StorageApplicationPermissions.FutureAccessList.Add(file, file.Name);
                    OutputTextBlock.Text = "The file '" + file.Name + "' was added to the FAL list and a token was stored.";
                }
            }
        }

        private void ShowListButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                if (MRURadioButton.IsChecked.Value)
                {
                    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); 
                        }

                        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)
                {
                    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); 
                        }

                        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.";
                    }
                }
            }
        }

        private async void OpenFromListButton_Click(object sender, RoutedEventArgs e)
        {
            if (acc.sampleFile != null)
            {
                if (MRURadioButton.IsChecked.Value)
                {
                    if (this.mruToken != null)
                    {
                        // 从指定的最近使用列表中检索文件
                        StorageFile file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(this.mruToken);

                        // 读取文件内容
                        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 (this.falToken != null)
                    {
                        StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(this.falToken);

                        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.";
                    }
                }
            }
        }
    }

 

13)复制一个文件

  使用StorageFile的CopyAsync方法来复制文件。

  修改我们的CopyAFile.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                 To copy 'Refact's Blog.refactor' to the documents library, click 'Copy'.
            </TextBlock>

            <Button Grid.Row="1" x:Name="CopyFileButton" Content="Copy" Margin="0,0,10,0"/>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改后台代码:

View Code
 public sealed partial class CopyAFile : Page
    {
        FileAccess acc = new FileAccess();
        public CopyAFile()
        {
            this.InitializeComponent();
            CopyFileButton.Click += new RoutedEventHandler(CopyFileButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                CopyFileButton.IsEnabled = false;
            }
        }

        private async void CopyFileButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                //复制
                StorageFile fileCopy = await file.CopyAsync(KnownFolders.DocumentsLibrary, "Refactor's Blog- Copy.refactor", NameCollisionOption.ReplaceExisting);
                OutputTextBlock.Text = "The file '" + file.Name + "' was copied and the new file was named '" + fileCopy.Name + "'.";
            }
        }
    }

 

14)删除一个文件

  使用StorageFile的DeleteAsync方法删除该文件。

  修改我们的DeleteAFile.xaml的xaml:

View Code
 <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" HorizontalAlignment="Left">
                To delete 'Refact's Blog.refactor', click 'Delete'.
            </TextBlock>

            <Button x:Name="DeleteFileButton" Grid.Row="1" Content="Delete" Margin="0,0,10,0"/>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

 

  修改我们的后台代码:

View Code
    public sealed partial class DeleteAFile : Page
    {
        FileAccess acc = new FileAccess();
        public DeleteAFile()
        {
            this.InitializeComponent();
             DeleteFileButton.Click += new RoutedEventHandler(DeleteFileButton_Click);
        }

        /// <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)
        {
            acc.Initialize();
            OutputTextBlock.Text = acc.ValidateFile(this.GetType());
            if (!string.IsNullOrEmpty(OutputTextBlock.Text))
            {
                DeleteFileButton.IsEnabled = false;
            }
        }

        private async void DeleteFileButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = acc.sampleFile;
            if (file != null)
            {
                string filename = file.Name;
                await file.DeleteAsync();
                acc.sampleFile = null;
                OutputTextBlock.Text = "The file '" + filename + "' was deleted";
            }
        }
    }

 

最后一个上效果图:

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第6张图片

点击 File Access

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第7张图片

点击Delete

图解使用Win8Api进行Metro风格的程序开发三----创建,读,写,复制和删除文件_第8张图片

未完待续,敬请期待...

转载请注明出处:http://www.cnblogs.com/refactor/

 

你可能感兴趣的:(metro)