Zip Folder And Its Content In Windows Runtime Apps

Here are the steps, 

Step 1:

Create a simple Windows Project. New Project, Visual C#, Windows 8, Windows, then click Blank App (Windows 8.1).

new

Step 2:

Let's add a button in MainPage.xaml :
  • A button with the Click event.

Complete MainPage.xaml code snippet is:

  1. <Page  
  2.     x:Class="ZipFolderContents.MainPage"  
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5.     xmlns:local="using:ZipFolderContents"  
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  8.     mc:Ignorable="d">  
  9.   
  10.     <Grid Background="#FF5D3FE4">  
  11.         <Button x:Name="btn_ZipContents" Content="Zip Folder" HorizontalAlignment="Left" Margin="451,144,0,0" VerticalAlignment="Top" Click="btn_ZipContents_Click" Height="60" Width="204"/>  
  12.     </Grid>  
  13. </Page>  
Step 3:

For testing purposes, we will read a folder from Documents Library, zip its content and save it in our application local folder.

So lets create a folder named ‘TestFolder’ in Documents Library. Inside the ‘TestFolder’, add some folders, text files, images, videos, etc.

file

folder

testfolder

Step 4:

For accessing Documents Library, we have to declar it in app capabilities. Right click on Package.appmanifest > View Code

View Code

In Package.appmanifest XML, update the Capabilities node with:
  1. <Capabilities>  
  2.     <Capability Name="internetClient" />  
  3.     <Capability Name="documentsLibrary" />  
  4.   </Capabilities>  
code

Step 5:

Now again in the Package.appmanifest designer view, we have to add File Type Association declarations as discussed here:  

Package

Step 6:

In the code behind: MainPage.xaml.cs

Update your code with this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. using System.IO.Compression;  
  6. using System.Linq;  
  7. using System.Runtime.InteropServices.WindowsRuntime;  
  8. using System.Threading.Tasks;  
  9. using Windows.Foundation;  
  10. using Windows.Foundation.Collections;  
  11. using Windows.Storage;  
  12. using Windows.UI.Popups;  
  13. using Windows.UI.Xaml;  
  14. using Windows.UI.Xaml.Controls;  
  15. using Windows.UI.Xaml.Controls.Primitives;  
  16. using Windows.UI.Xaml.Data;  
  17. using Windows.UI.Xaml.Input;  
  18. using Windows.UI.Xaml.Media;  
  19. using Windows.UI.Xaml.Navigation;  
  20.   
  21. // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238  
  22.   
  23. namespace ZipFolderContents  
  24. {  
  25.     /// <summary>  
  26.     /// An empty page that can be used on its own or navigated to within a Frame.  
  27.     /// </summary>  
  28.     public sealed partial class MainPage : Page  
  29.     {  
  30.         public MainPage()  
  31.         {  
  32.             this.InitializeComponent();  
  33.         }  
  34.   
  35.         private async void btn_ZipContents_Click(object sender, RoutedEventArgs e)  
  36.         {  
  37.             try  
  38.             {  
  39.                 string appFolderPath = ApplicationData.Current.LocalFolder.Path;  
  40.                 StorageFolder destinationFolder = await StorageFolder.GetFolderFromPathAsync(appFolderPath);  
  41.   
  42.                 //Gets the folder named TestFolder from Documents Library Folder  
  43.                 StorageFolder sourceFolder = await KnownFolders.DocumentsLibrary.GetFolderAsync("TestFolder");    
  44.   
  45.                 //Creates a zip file named TestFolder.zip in Local Folder  
  46.                 StorageFile zipFile = await destinationFolder.CreateFileAsync("TestFolder.zip", CreationCollisionOption.ReplaceExisting);  
  47.                 Stream zipToCreate = await zipFile.OpenStreamForWriteAsync();  
  48.                 ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Update);  
  49.   
  50.                 await ZipFolderContentsHelper(sourceFolder, archive, sourceFolder.Path);  
  51.                 archive.Dispose();  
  52.                 MessageDialog msg = new MessageDialog("Success");  
  53.                 await msg.ShowAsync();  
  54.             }  
  55.             catch (Exception ex)  
  56.             {  
  57.                 Debug.WriteLine(ex.ToString());  
  58.             }  
  59.         }  
  60.   
  61.         private async Task ZipFolderContentsHelper(StorageFolder sourceFolder, ZipArchive archive, string sourceFolderPath)  
  62.         {  
  63.             IReadOnlyList<StorageFile> files = await sourceFolder.GetFilesAsync();  
  64.   
  65.             foreach (StorageFile file in files)  
  66.             {  
  67.                 ZipArchiveEntry readmeEntry = archive.CreateEntry(file.Path.Remove(0, sourceFolderPath.Length));  
  68.                 byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(file));  
  69.                 using (Stream entryStream = readmeEntry.Open())  
  70.                 {  
  71.                     await entryStream.WriteAsync(buffer, 0, buffer.Length);  
  72.                 }  
  73.             }  
  74.   
  75.             IReadOnlyList<StorageFolder> subFolders = await sourceFolder.GetFoldersAsync();  
  76.   
  77.             if (subFolders.Count() == 0)  
  78.             {  
  79.                 return;  
  80.             }  
  81.   
  82.             foreach (StorageFolder subfolder in subFolders)  
  83.             {  
  84.                 await ZipFolderContentsHelper(subfolder, archive, sourceFolderPath);  
  85.             }  
  86.         }  
  87.     }  
  88. }  

Step 7:

Run the application and click on Zip Folder button, you will get a success message if everything is OK. And ‘TestFolder.zip’ is created in: This PC, C , Users > [Your User Name] > AppData, Local, Packages, [App package name] > LocalState

LocalState

That’s it.
Thanks, Happy Coding!

 
Read more articles on Windows Runtime Apps:


Similar Articles