Multiple files and folders can be zipped or compressed easily by using AddFolderAsync method in C1ZipEntryCollection class. Use the following code to select multiple files and folders and then compress all of them together. In this code example, the following button click events are defined:
Complete the following steps:
XAML |
Copy Code
|
---|---|
<Page x:Class="ZipUWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:ZipUWP" xmlns:flexGrid="using:C1.Xaml.FlexGrid" xmlns:c1="using:C1.Xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> |
XAML |
Copy Code
|
---|---|
<Page.Resources> <ResourceDictionary> <ResourceDictionary.ThemeDictionaries> <ResourceDictionary x:Key="Default"> <SolidColorBrush x:Key="ApplicationPageBackgroundThemeBrush" Color="#FF1D1D1D"/> </ResourceDictionary> <ResourceDictionary x:Key="Light"> <SolidColorBrush x:Key="ApplicationPageBackgroundThemeBrush" Color="#FFF2F2F2"/> </ResourceDictionary> </ResourceDictionary.ThemeDictionaries> <Style x:Key="bigButton" TargetType="Button" > <Setter Property="Width" Value="124" /> <Setter Property="FontSize" Value="16" /> <Setter Property="Margin" Value="10,0,0,0" /> <Setter Property="Padding" Value="2" /> </Style> <Style x:Key="smallButton" TargetType="Button" > <Setter Property="Width" Value="100" /> <Setter Property="FontSize" Value="14" /> <Setter Property="Margin" Value="4,0,0,0" /> <Setter Property="Padding" Value="0" /> </Style> </ResourceDictionary> </Page.Resources> <Grid> <Grid x:Name="_mainpage"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <RelativePanel Grid.Row="0"> <RelativePanel Name="_compressPanel" > <TextBlock Name="_compress" Text="compress" FontSize="16" Width="100"/> <Button Name="_btnPickSingleFolder" Content="PickSingleFolder" Click="_btnPickFolder_Click"/> <Button Name="_btnPickFiles" Content="PickFiles" RelativePanel.RightOf="_btnPickSingleFolder" RelativePanel.AlignTopWith="_btnPickSingleFolder" Click="_btnPickFiles_Click"/> <Button Name="_btnCompress" Content="Compress" RelativePanel.RightOf="_btnPickFiles" RelativePanel.AlignTopWith="_btnPickSingleFolder" Click="_btnCompress_Click" IsEnabled="False" Height="51" Margin="4,0,-36,-47" Width="136"/> </RelativePanel> <RelativePanel Name="_extractPanel" > <TextBlock Name="_extract" Text="extract" FontSize="16" Width="100"/> <Button Name="_btnOpen" Content="Open" Click="_btnOpen_Click" /> <Button Name="_btnExtract" Content="Extract" RelativePanel.RightOf="_btnOpen" RelativePanel.AlignTopWith="_btnOpen" Click="_btnExtract_Click" IsEnabled="False"/> </RelativePanel> <RelativePanel Name="_actionPanel" > <Button Name="_btnRemove" Content="Remove" Click="_btnRemove_Click" IsEnabled="False" /> <Button Name="_btnView" Content="View" Click="_btnView_Click" IsEnabled="False"/> <Button Name="_btnClear" Content="Clear" Click="_btnClear_Click" /> <ListBox Name="listBox1" /> </RelativePanel> </RelativePanel> <ProgressBar x:Name="progressBar" Grid.Row="1" Width="400" Canvas.ZIndex="10" HorizontalAlignment="Center" VerticalAlignment="Center" IsIndeterminate="True" Visibility="Collapsed" Background="Black"/> <flexGrid:C1FlexGrid BorderBrush="Gray" BorderThickness="1" Margin="4" x:Name="_flex" Grid.Row="2" SelectionMode="Row" HeadersVisibility="Column" AllowResizing="Columns" HeaderGridLinesBrush="Transparent" AutoGenerateColumns="False" > <flexGrid:C1FlexGrid.Columns> <flexGrid:Column Binding="{Binding FileName}" Header="Name" /> <!--x:Uid="/ZipSamplesLib/Resources/Name"--> <flexGrid:Column Binding="{Binding SizeUncompressedLong}" Header="Size" Format="n0" /> <!--x:Uid="/ZipSamplesLib/Resources/Size"--> <flexGrid:Column Binding="{Binding SizeCompressedLong}" Header="Compressed" Format="n0" /> <!--x:Uid="/ZipSamplesLib/Resources/Compressed"--> <flexGrid:Column Binding="{Binding CompressionRatio}" Header="Ratio" Format="p0" /> <!--x:Uid="/ZipSamplesLib/Resources/Ratio"--> <flexGrid:Column Binding="{Binding CRC32}" Header="Crc" Format="x0" /> <!--x:Uid="/ZipSamplesLib/Resources/CRC"--> <flexGrid:Column Binding="{Binding Attributes}" Header="Attributes" /> <!--x:Uid="/ZipSamplesLib/Resources/Attributes"--> </flexGrid:C1FlexGrid.Columns> </flexGrid:C1FlexGrid> </Grid> <RelativePanel Name="_preview" Visibility="Collapsed"> <TextBlock Name="_text" Text="text" FontSize="28" Margin="0 0 40 0"/> <Button Name="_btnClosePreview" Content="ClosePreview" Click="_btnClosePreview_Click_1" RelativePanel.RightOf="_text" Margin="30,0,40,0" Width="100"/> <TextBox Name="_tbContent" IsReadOnly="True" AcceptsReturn="True" FontFamily="Courier New" Background="White" RelativePanel.Below="_btnClosePreview" Margin="10"/> </RelativePanel> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="WindowSizeStates"> <!-- First set of VisualStates are simple responsive states based on window size. AdaptiveTrigger is a built-in trigger that XAML knows to automatically trigger based on window size --> <VisualState> <VisualState.StateTriggers> <!-- Trigger below indicates that this VisualState is to be applied when the current window width is >= 481 effective pixels --> <AdaptiveTrigger MinWindowWidth="481" /> </VisualState.StateTriggers> <VisualState.Setters> <!-- Simplified Setter statements are used to move elements around to optimize for more available space --> <Setter Target="_btnPickSingleFolder.(RelativePanel.RightOf)" Value="_compress" /> <Setter Target="_btnPickSingleFolder.Style" Value="{StaticResource bigButton}" /> <Setter Target="_btnPickFiles.(RelativePanel.RightOf)" Value="_btnPickSingleFolder" /> <Setter Target="_btnPickFiles.Style" Value="{StaticResource bigButton}" /> <Setter Target="_btnCompress.(RelativePanel.RightOf)" Value="_btnPickFiles" /> <Setter Target="_btnCompress.Style" Value="{StaticResource bigButton}" /> <Setter Target="_extractPanel.(RelativePanel.Below)" Value="_compressPanel" /> <Setter Target="_extractPanel.Margin" Value="0,10,0,0" /> <Setter Target="_btnOpen.(RelativePanel.RightOf)" Value="_extract" /> <Setter Target="_btnOpen.Style" Value="{StaticResource bigButton}" /> <Setter Target="_btnExtract.Style" Value="{StaticResource bigButton}" /> <Setter Target="_actionPanel.(RelativePanel.Below)" Value="_extractPanel" /> <Setter Target="_actionPanel.Margin" Value="100,10,0,0" /> <Setter Target="_btnRemove.Style" Value="{StaticResource bigButton}" /> <Setter Target="_btnView.(RelativePanel.RightOf)" Value="_btnRemove" /> <Setter Target="_btnView.Style" Value="{StaticResource bigButton}" /> <Setter Target="_btnClear.(RelativePanel.RightOf)" Value="_btnView" /> <Setter Target="_btnClear.Style" Value="{StaticResource bigButton}" /> <Setter Target="_flex.FontSize" Value="16" /> </VisualState.Setters> </VisualState> <VisualState> <VisualState.StateTriggers> <!-- Trigger below indicates that this VisualState is to be applied when current window width is >=0 and <481 effective pixels --> <AdaptiveTrigger MinWindowWidth="0" /> </VisualState.StateTriggers> <VisualState.Setters> <!-- Simplified Setter statements are used to move elements around to optimize for lesser available space --> <Setter Target="_compress.FontSize" Value="12" /> <Setter Target="_extract.FontSize" Value="12" /> <Setter Target="_btnPickSingleFolder.(RelativePanel.Below)" Value="_compress" /> <Setter Target="_btnPickSingleFolder.Style" Value="{StaticResource smallButton}" /> <Setter Target="_btnPickFiles.(RelativePanel.RightOf)" Value="_btnPickSingleFolder" /> <Setter Target="_btnPickFiles.Style" Value="{StaticResource smallButton}" /> <Setter Target="_btnCompress.(RelativePanel.RightOf)" Value="_btnPickFiles" /> <Setter Target="_btnCompress.Style" Value="{StaticResource smallButton}" /> <Setter Target="_extractPanel.(RelativePanel.Below)" Value="_compressPanel" /> <Setter Target="_extractPanel.Margin" Value="0,10,0,0" /> <Setter Target="_btnOpen.(RelativePanel.Below)" Value="_extract" /> <Setter Target="_btnOpen.Style" Value="{StaticResource smallButton}" /> <Setter Target="_btnExtract.Style" Value="{StaticResource smallButton}" /> <Setter Target="_actionPanel.(RelativePanel.Below)" Value="_extractPanel" /> <Setter Target="_actionPanel.Margin" Value="0,10,0,0" /> <Setter Target="_btnRemove.Style" Value="{StaticResource smallButton}" /> <Setter Target="_btnView.(RelativePanel.RightOf)" Value="_btnRemove" /> <Setter Target="_btnView.Style" Value="{StaticResource smallButton}" /> <Setter Target="_btnClear.(RelativePanel.RightOf)" Value="_btnView" /> <Setter Target="_btnClear.Style" Value="{StaticResource smallButton}" /> <Setter Target="_flex.FontSize" Value="10" /> <Setter Target="_btnClosePreview.Margin" Value="0,0,5,0" /> <Setter Target="_btnClosePreview.Width" Value="80" /> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </Page> |
C# |
Copy Code
|
---|---|
using System.IO; using C1.C1Zip; using Windows.Storage.Pickers; using Windows.Storage; using Windows.UI.Popups; |
C# |
Copy Code
|
---|---|
namespace ZipUWP { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { C1ZipFile _zip; CollectionViewSource _cvs = new CollectionViewSource(); MemoryStream zipMemoryStream = null; public MainPage() { this.InitializeComponent(); _flex.SelectedItemChanged += _flex_SelectedItemChanged; // bind grid to entries collection } void _flex_SelectedItemChanged(object sender, EventArgs e) { if (_flex.SelectedItem != null) { _btnView.IsEnabled = true; _btnRemove.IsEnabled = true; } else { _btnView.IsEnabled = false; _btnRemove.IsEnabled = false; } } void RefreshView() { //var sel = _flex.SelectedItem; _flex.ItemsSource = null; if (_zip == null) { return; } _flex.ItemsSource = _zip.Entries; if (_zip.Entries.Count == 0) { _btnCompress.IsEnabled = false; _btnRemove.IsEnabled = false; _btnView.IsEnabled = false; _btnExtract.IsEnabled = false; } //_flex.SelectedItem = sel; } // open an existing zip file async void _btnOpen_Click(object sender, RoutedEventArgs e) { try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".zip"); StorageFile _zipfile = await picker.PickSingleFileAsync(); if (_zipfile != null) { Clear(); progressBar.Visibility = Visibility.Visible; if (_zip == null) { _zip = new C1ZipFile(new System.IO.MemoryStream(), true); } var stream = await _zipfile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); _zip.Open(stream.AsStream()); _btnExtract.IsEnabled = true; RefreshView(); } } catch (Exception x) { System.Diagnostics.Debug.WriteLine(x.Message); } progressBar.Visibility = Visibility.Collapsed; } // remove selected entries from zip void _btnRemove_Click(object sender, RoutedEventArgs e) { foreach (C1ZipEntry entry in _flex.SelectedItems) { _zip.Entries.Remove(entry.FileName); } RefreshView(); } // show a preview of the selected entry void _btnView_Click(object sender, RoutedEventArgs e) { var entry = _flex.SelectedItem as C1ZipEntry; if (entry != null) { using (var stream = entry.OpenReader()) { var sr = new System.IO.StreamReader(stream); _tbContent.Text = sr.ReadToEnd(); } _preview.Visibility = Visibility.Visible; _mainpage.Visibility = Visibility.Collapsed; } } // close the preview pane by hiding it void _btnClosePreview_Click_1(object sender, RoutedEventArgs e) { _preview.Visibility = Visibility.Collapsed; _mainpage.Visibility = Visibility.Visible; } // add files by folder private async void _btnPickFolder_Click(object sender, RoutedEventArgs e) { try { FolderPicker folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add("*"); StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync(); if (pickedFolder != null) { if (_btnExtract.IsEnabled) { Clear(); } progressBar.Visibility = Visibility.Visible; if (zipMemoryStream == null) { zipMemoryStream = new MemoryStream(); } if (_zip == null) { _zip = new C1ZipFile(zipMemoryStream, true); } await _zip.Entries.AddFolderAsync(pickedFolder); _btnCompress.IsEnabled = true; } } catch { } RefreshView(); progressBar.Visibility = Visibility.Collapsed; } // add files private async void _btnPickFiles_Click(object sender, RoutedEventArgs e) { try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add("*"); var files = await picker.PickMultipleFilesAsync(); if (files != null) { if (files.Count == 0) { return; } if (_btnExtract.IsEnabled) { Clear(); } progressBar.Visibility = Visibility.Visible; if (zipMemoryStream == null) { zipMemoryStream = new MemoryStream(); } if (_zip == null) { _zip = new C1ZipFile(zipMemoryStream, true); } foreach (var f in files) { await _zip.Entries.AddAsync(f); } _btnCompress.IsEnabled = true; } } catch { } RefreshView(); progressBar.Visibility = Visibility.Collapsed; } private async void _btnCompress_Click(object sender, RoutedEventArgs e) { try { if (zipMemoryStream != null) { FileSavePicker fileSavePicker = new FileSavePicker(); fileSavePicker.FileTypeChoices.Add("Zip", new List<string> { ".zip" }); fileSavePicker.DefaultFileExtension = ".zip"; fileSavePicker.SuggestedFileName = "NewFolder"; fileSavePicker.CommitButtonText = "Save"; fileSavePicker.SuggestedStartLocation = PickerLocationId.ComputerFolder; StorageFile pickedSaveFile = await fileSavePicker.PickSaveFileAsync(); await FileIO.WriteBytesAsync(pickedSaveFile, zipMemoryStream.ToArray()); MessageDialog md = new MessageDialog("Compress Successfully, the path is :" + pickedSaveFile.Path); md.ShowAsync(); } } catch { } RefreshView(); } private async void _btnExtract_Click(object sender, RoutedEventArgs e) { try { FolderPicker folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add("*"); StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync(); progressBar.Visibility = Visibility.Visible; foreach (var entry in _zip.Entries) { var name = entry.FileName; await entry.Extract(pickedFolder, name); } MessageDialog md = new MessageDialog("Extract Successfully, the path is :" + pickedFolder.Path); md.ShowAsync(); } catch { } RefreshView(); progressBar.Visibility = Visibility.Collapsed; } private void _btnClear_Click(object sender, RoutedEventArgs e) { Clear(); } private void Clear() { _flex.ItemsSource = null; if (zipMemoryStream != null) { zipMemoryStream.Flush(); zipMemoryStream.Dispose(); } zipMemoryStream = null; _btnCompress.IsEnabled = false; _btnExtract.IsEnabled = false; if (_zip != null) { _zip.Close(); _zip = null; } } } } |
Note that the above code has limitation that it can not add empty folder into zip file.