图解使用Win8Api进行Metro风格的程序开发九----解压缩

我们紧接着上篇,这篇将介绍如何使用Windows.Storage.Compression API来实现解压缩
-----------------------------------我是华丽的分割线-----------------------------------------
我们紧接着上篇,这篇将介绍如何使用Windows.Storage.Compression API来实现解压缩。

本篇将介绍如下五个方面:
  a)读取未压缩文件的数据
  b)使用指定的压缩算法压缩
  c)写压缩数据到新文件
  d)从压缩文件中读数据
  e)解压数据

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

  创建方法请参照前一篇.
3)此时的解决方案结构如下:

 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

            #region Group3
            var group3 = new SampleDataGroup("AccountPictureName",
              "Use Windows.System.UserProfile API",
              "Account Picture Name",
              "Assets/AccountPictureName.jpg",
              "");
            group3.Items.Add(new SampleDataItem("AccountPictureName-GetUserDisplayName",
                    "Get User DisplayName",
                    "Use UserInformation.GetDisplayNameAsync Get User DisplayName",
                    "Assets/AccountPictureName.jpg",
                    "Use UserInformation.GetDisplayNameAsync",
                    "",
                    group3,
                    typeof(GetUserDisplayName)));
            group3.Items.Add(new SampleDataItem("AccountPictureName-GetUserFirstLastName",
                    "Get First Last Name",
                    "Use UserInformation.GetFirstNameAsync,GetLastNameAsync Get First Name",
                    "Assets/AccountPictureName.jpg",
                    "Use UserInformation.GetFirstNameAsync ",
                    "",
                    group3,
                    typeof(GetUserFirstLastName)));
            group3.Items.Add(new SampleDataItem("AccountPictureName-GetAccountPicture",
                    "Get Account Picture",
                    "Use UserInformation.GetAccountPicture Get Account Picture",
                    "Assets/AccountPictureName.jpg",
                    "Use UserInformation.GetAccountPicture",
                    "",
                    group3,
                    typeof(GetAccountPicture)));
            group3.Items.Add(new SampleDataItem("AccountPictureName-SetAccountPictureAndListen",
                    "Set AccountPicture And Listen",
                    "Use UserInformation.SetAccountPicturesAsync Set AccountPicture",
                    "Assets/AccountPictureName.jpg",
                    "Use UserInformation.SetAccountPicturesAsync",
                    "",
                    group3,
                    typeof(SetAccountPictureAndListen)));
            this.AllGroups.Add(group3);
            #endregion

            #region Group4
            var group4 = new SampleDataGroup("ApplicationSettings",
              "ApplicationSettings",
              " Use the Windows.UI.ApplicationSettings namespace and WinJS.UI.SettingsFlyout",
              "Assets/ApplicationSettings.jpg",
              "");
            group4.Items.Add(new SampleDataItem("ApplicationSettings-Default",
                    "Default behavior with no settings integration",
                    "Default behavior ",
                    "Assets/ApplicationSettings.jpg",
                    "Default behavior with no settings integration",
                    "",
                    group4,
                    typeof(Default)));
            group4.Items.Add(new SampleDataItem("ApplicationSettings-AddSettings",
                    "Add settings commands to the settings charm",
                    "Add settings",
                    "Assets/ApplicationSettings.jpg",
                    "Add settings commands to the settings charm ",
                    "",
                    group4,
                    typeof(AddSettings)));

            this.AllGroups.Add(group4);
            #endregion

            #region Group5
            var Group5 = new SampleDataGroup("AssociationLaunching",
              "Use Windows.System.Launcher API",
              "Association Launching",
              "Assets/AssociationLaunching.jpg",
              "");
            Group5.Items.Add(new SampleDataItem("AssociationLaunching-LaunchFile",
                    "Launching a file",
                    "Use Windows.System.Launcher.LaunchFileAsync",
                    "Assets/AssociationLaunching.jpg",
                    "Use Windows.System.Launcher.LaunchFileAsync",
                    "",
                    Group5,
                    typeof(LaunchFile)));
            Group5.Items.Add(new SampleDataItem("AssociationLaunching-LaunchUri",
                    "Launching a URI",
                    "Use Windows.System.Launcher.LaunchUriAsync",
                    "Assets/AssociationLaunching.jpg",
                    "Use Windows.System.Launcher.LaunchUriAsync",
                    "",
                    Group5,
                    typeof(LaunchUri)));
            Group5.Items.Add(new SampleDataItem("AssociationLaunching-ReceiveFile",
                    "Receiving a file",
                    "Receiving a file",
                    "Assets/AssociationLaunching.jpg",
                    "Receiving a file",
                    "",
                    Group5,
                    typeof(ReceiveFile)));
            Group5.Items.Add(new SampleDataItem("AssociationLaunching-ReceiveUri",
                    "Receiving a URI",
                    "Receiving a URI",
                    "Assets/AssociationLaunching.jpg",
                    "Receiving a URI",
                    "",
                    Group5,
                    typeof(ReceiveUri)));
            this.AllGroups.Add(Group5);
            #endregion

            #region Group6
            var Group6 = new SampleDataGroup("BackgroundTransfer",
              "Use Windows.Networking.BackgroundTransfer API",
              "BackgroundDownloader And BackgroundUploader",
              "Assets/BackgroundTransfer.jpg",
              "");
            Group6.Items.Add(new SampleDataItem("BackgroundTransfer-DownloadFile",
                    "Download Files",
                    "Use BackgroundDownloader",
                    "Assets/BackgroundTransfer.jpg",
                    "BackgroundDownloader",
                    "",
                    Group6,
                    typeof(DownloadFile)));
            Group6.Items.Add(new SampleDataItem("BackgroundTransfer-UploadFile",
                    "Upload Files",
                    "Use BackgroundUploader",
                    "Assets/BackgroundTransfer.jpg",
                    "BackgroundUploader",
                    "",
                    Group6,
                    typeof(UploadFile)));

            this.AllGroups.Add(Group6);
            #endregion

            #region Group7
            var Group7 = new SampleDataGroup("Clipboard",
              "Use Windows.ApplicationModel.DataTransfer API",
              "ClipboardOperation",
              "Assets/Clipboard.jpg",
              "");
            Group7.Items.Add(new SampleDataItem("Clipboard-CopyAndPasteText",
                    "Copy and paste text",
                    "Use Clipboard.GetContent,Clipboard.SetContent",
                    "Assets/Clipboard.jpg",
                    "Clipboard.GetContent,Clipboard.SetContent",
                    "",
                    Group7,
                    typeof(CopyAndPasteText)));
            Group7.Items.Add(new SampleDataItem("Clipboard-CopyAndPasteImage",
                    "Copy and paste an image",
                    "Use Clipboard.GetContent,Clipboard.SetContent",
                    "Assets/Clipboard.jpg",
                    "Clipboard.GetContent,Clipboard.SetContent",
                    "",
                    Group7,
                    typeof(CopyAndPasteImage)));
            Group7.Items.Add(new SampleDataItem("Clipboard-CopyAndPasteFile",
                    "Copy and paste files",
                    "Use Clipboard.GetContent,Clipboard.SetContent",
                    "Assets/Clipboard.jpg",
                    "Clipboard.GetContent,Clipboard.SetContent",
                    "",
                    Group7,
                    typeof(CopyAndPasteFile)));
            Group7.Items.Add(new SampleDataItem("Clipboard-OtherClipboardOperation",
                    "Other Clipboard operations",
                    "Use Clipboard.GetContent,Clipboard.SetContent",
                    "Assets/Clipboard.jpg",
                    "Clipboard.GetContent,Clipboard.SetContent",
                    "",
                    Group7,
                    typeof(OtherClipboardOperation)));

            this.AllGroups.Add(Group7);
            #endregion

            #region Group8
            var Group8 = new SampleDataGroup("Compression",
              "Use Windows.Storage.Compression API",
              "Compression And Decompression",
              "Assets/Compression.jpg",
              "");
            Group8.Items.Add(new SampleDataItem("Compression-CompressionAndDecompression",
                    "Compression And Decompression",
                    "Use Windows.Storage.Compression API",
                    "Assets/Compression.jpg",
                    "Compression And Decompression",
                    "",
                    Group8,
                    typeof(CompressionAndDecompression)));

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

 

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

  点击 Compression

6)压缩和解压文件
  我们使用Compressor压缩文件,
  使用Decompression解压文件.
  首先修改Package.appxmanifest文件:


  修改CompressionAndDecompression.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 x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >
                Demonstrates how to use the Windows.Storage.Compression namespace in C#.
                <LineBreak/>
                <LineBreak/>
                Compression algorithms:
                <LineBreak/>
                DEFAULT: No compression algorithms explicitly specified. Xpress is used by default.
                <LineBreak/>
                XPRESS: Compression ratio is fair. Fastest compression and decompression speeds. Lowest memory requirement.
                <LineBreak/>
                XPRESSHUFF: Compression ratio is fair. Fast compression and decompression speeds. Low memory requirement.
                <LineBreak/>
                MSZIP: Compression ratio is high. Normal compression speed and fast decompression speed. Low memory requirement.
                <LineBreak/>
                LZMS: Compression ratio is highest. Medium compression speed and normal decompression speed. High memory requirement.
                <LineBreak/>
            </TextBlock>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
                <Button x:Name="Default" Content="DEFAULT (XPRESS)" Margin="0,0,10,0" Click="Default_Click"/>
                <Button x:Name="Xpress"  Content="XPRESS" Margin="0,0,10,0" Click="Xpress_Click"/>
                <Button x:Name="XpressHuff"  Content="XPRESSHUFF" Margin="0,0,10,0" Click="XpressHuff_Click"/>
                <Button x:Name="Mszip"  Content="MSZIP" Margin="0,0,10,0" Click="Mszip_Click"/>
                <Button x:Name="Lzms"  Content="LZMS" Margin="0,0,10,0" Click="Lzms_Click"/>
            </StackPanel>
        </Grid>

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

   修改后台代码:

View Code
    public sealed partial class CompressionAndDecompression : Page
    {
        public CompressionAndDecompression()
        {
            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)
        {
        }

        /// <summary>
        /// This is the main  worker.
        /// </summary>
        /// <param name="Algorithm">
        /// Comression algorithm to use. If no value is provided compressor will be created using
        /// Compressor(IInputStream) constructor, otherwise extended version will be used:
        /// Compressor(IInputStream, CompressAlgorithm, uint)
        /// </param>
        private async void DoWork(CompressAlgorithm? Algorithm)
        {
            try
            {
                OutputText.Text = "";
                OutputText.Text = "Working...";

                var picker = new FileOpenPicker();
                picker.FileTypeFilter.Add("*");
                //选择一个文件
                var originalFile = await picker.PickSingleFileAsync();
                if (originalFile == null)
                {
                    throw new OperationCanceledException("No file has been selected");
                }

                OutputText.Text += String.Format("\"{0}\" has been picked\n", originalFile.Name);

                var compressedFilename = originalFile.Name + ".compressed";
                //在文档库创建文件
                //注意此处需要先声明中加文件关联.compressed和.decompressed,否则文档库拒绝访问
                var compressedFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(compressedFilename, CreationCollisionOption.GenerateUniqueName);
                OutputText.Text += String.Format("\"{0}\" has been created to store compressed data\n", compressedFile.Name);

                //打开一个随机访问流,读取文件内容
                using (var originalInput = await originalFile.OpenReadAsync())
                //在压缩目标文件打开一个随机访问流
                using (var compressedOutput = await compressedFile.OpenAsync(FileAccessMode.ReadWrite))
                //创建压缩对象
                using (var compressor = !Algorithm.HasValue ?
                    new Compressor(compressedOutput.GetOutputStreamAt(0)) :
                    new Compressor(compressedOutput.GetOutputStreamAt(0), Algorithm.Value, 0))
                {
                    OutputText.Text += "All streams wired for compression\n";
                    //实现压缩
                    var bytesCompressed = await RandomAccessStream.CopyAsync(originalInput,compressor);
                    //完成压缩
                    var finished = await compressor.FinishAsync();
                    OutputText.Text += String.Format("Compressed {0} bytes into {1}\n", bytesCompressed, compressedOutput.Size);
                }

                var decompressedFilename = originalFile.Name + ".decompressed";
                var decompressedFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(decompressedFilename, CreationCollisionOption.GenerateUniqueName);
                OutputText.Text += String.Format("\"{0}\" has been created to store decompressed data\n", decompressedFile.Name);

                //打开一个顺序访问流来读取文件内容
                using (var compressedInput = await compressedFile.OpenSequentialReadAsync())
                //创建解压对象
                using (var decompressor = new Decompressor(compressedInput))
                using (var decompressedOutput = await decompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    OutputText.Text += "All streams wired for decompression\n";
                    //解压
                    var bytesDecompressed = await RandomAccessStream.CopyAsync(decompressor, decompressedOutput);
                    OutputText.Text += String.Format("Decompressed {0} bytes of data\n", bytesDecompressed);
                }

                OutputText.Text += "All done";
            }
            catch (Exception ex)
            {
                OutputText.Text += ex.Message;
            }
        }

        private void Default_Click(object sender, RoutedEventArgs e)
        {
            DoWork(null);
        }

        private void Xpress_Click(object sender, RoutedEventArgs e)
        {
            DoWork(CompressAlgorithm.Xpress);
        }

        private void XpressHuff_Click(object sender, RoutedEventArgs e)
        {
            DoWork(CompressAlgorithm.XpressHuff);
        }

        private void Mszip_Click(object sender, RoutedEventArgs e)
        {
            DoWork(CompressAlgorithm.Mszip);
        }

        private void Lzms_Click(object sender, RoutedEventArgs e)
        {
            DoWork(CompressAlgorithm.Lzms);
        }
    }

   效果图

 

未完待续,敬请期待...
转载请注明出处:http://www.cnblogs.com/refactor/

posted on 2012-06-20 09:22  refactor  阅读(1504)  评论(0编辑  收藏  举报

导航