USING IRONZIP

.NET MAUI Data Extraction SDK (Developer Tutorial)

Published December 12, 2023
Share:

Introduction

.NET MAUI, or .NET Multi-platform App UI, is a framework for building cross-platform applications. It allows developers to create applications with a single codebase that runs on Windows, macOS, iOS, Android, and or any other device. Similar to react native, but works with C# instead of JavaScript.

.NET MAUI allows C# developers to build hassle-free mobile applications, desktop apps, from a single environment. Microsoft .NET MAUI provides full-fledged documentation and resources, to help developers ease and optimize the app development process.

In this article, we'll explore the integration of IronZIP, a powerful C# ZIP Archive Library, with .NET MAUI for data extraction purposes.

How to Extract Data from Zip Archives

  1. Create a Visual Studio .NET MAUI Project
  2. Install C# Zip Library using NuGet
  3. Design Data Extraction App Interface
  4. Implement Create Zip and Extract Zip Methods
  5. Run the application and verify the results

Introduction to IronZIP

IronZIP is a comprehensive C# ZIP archive library designed for creating, reading, and extracting archives in .NET. It supports a wide range of archive formats, including ZIP, TAR, GZIP, and BZIP2. IronZIP is compatible with various .NET versions, such as .NET 7, 6, 5, Core, Standard, and Framework.

It is cross-platform, making it suitable for C#, F#, and VB.NET applications running on Windows, Linux, Mac, iOS, Android, Docker, Azure, and AWS.

Key Features of IronZIP include:

  • Cross-platform support for various operating systems.
  • Compatibility with different .NET versions and project types.
  • Support for creating, reading, and extracting ZIP, TAR, GZIP, and BZIP2 archives.
  • Integration with .NET MAUI for building multi-platform applications.

Prerequisites

Before getting started, ensure that you have the following prerequisites:

  1. Visual Studio with .NET MAUI workload installed.
  2. IronZIP library added to your .NET MAUI project.

Steps to Create .NET MAUI Application in Visual Studio

  1. Open Visual Studio and click on "Create a New project."
  2. Select the .NET MAUI App project template and click Next.

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 1

  3. Configure Project Settings, Project Name, and Location. Click Next.

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 2

  4. From Additional Information, select the right .NET Framework. IronZIP supports the latest version of .NET Framework so you can choose that.

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 3

  5. Click Create to create the .NET MAUI App for Zip Data Extraction using the IronZIP library.

Install IronZIP

To integrate IronZIP into your .NET MAUI project, follow these steps:

  1. Open Solution Explorer from View.

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 4

  2. Right-click on your project in Solution Explorer.
  3. Select "Manage NuGet Packages for Solution."

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 5

  4. In the NuGet browse tab, Search for "IronZIP" and install the package for your project.

    .NET MAUI Data Extraction SDK (Developer Tutorial): Figure 6

  5. In the Preview Changes Dialog box, click "Apply" to make changes and then click "Accept" to accept the IronZIP License.
  6. NuGet will finish Installation and a confirmation message will appear.

Now then, everything is installed and set up, let's move to the Data extraction task of creating a Zip Extractor in .NET MAUI.

Steps to Create a Zip Extractor

Step 1 Design Apps Interface

In this section, we'll focus on designing the user interface for your .NET MAUI application. Open the MainPage.xaml file in your project folder and add the necessary XAML code to create a user-friendly interface.

Here, we'll need two buttons, one for creating zip files and a second for extracting zip files. A few labels are also required to give appropriate messages. The following code example shows the xaml code of the design:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppDataExtraction.MainPage">
    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">
            <Label
                Text="IronZIP - A Zip Library to Create and Extract Zip Content!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />
            <Label
                Text="Welcome to .NET Multi-platform App UI"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />
            <Button
                x:Name="OpenFileBtn"
                Text="Extract Zip File"
                SemanticProperties.Hint="Opens the File Picker"
                Clicked="OnSelectFileButtonClicked"
                HorizontalOptions="Center" />
            <Button
                 x:Name="OpenFilesBtn"
                 Text="Create Zip"
                 SemanticProperties.Hint="Opens the File Picker"
                 Clicked="OnSelectFilesButtonClicked"
                 HorizontalOptions="Center" />  
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
XML

Run the application, and you'll see the output as regular Windows forms on the screen.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 7

Step 2 Implement the Code

1. Create Zip

Open the MainPage.xaml.cs file and create the "Create Zip" functionality. Implement the OnSelectFilesButtonClicked method to allow opening the FilePicker and selecting multiple files of any type for creating a zip file.

Then create a list of all the paths from selected files. Finally, pass it to the CreateZip method where IronZIP will create a zip file using all the file paths seamlessly within a second.

The following code example shows how to achieve this task.

private async void OnSelectFilesButtonClicked(object sender, EventArgs e)
{
    try
    {
        var status = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Alert!", "Storage Access Denied", "Ok");
            return;
        }
        // Select Multiple files of any type
        var results = await FilePicker.PickMultipleAsync();
        if (results != null)
        {
            var selectedFilePaths = new List<string>();
            foreach (var file in results)
            {
                // Add File Full Path to the list one by one
                selectedFilePaths.Add(file.FullPath);
            }
            CreateZip(selectedFilePaths);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
}
private async void OnSelectFilesButtonClicked(object sender, EventArgs e)
{
    try
    {
        var status = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Alert!", "Storage Access Denied", "Ok");
            return;
        }
        // Select Multiple files of any type
        var results = await FilePicker.PickMultipleAsync();
        if (results != null)
        {
            var selectedFilePaths = new List<string>();
            foreach (var file in results)
            {
                // Add File Full Path to the list one by one
                selectedFilePaths.Add(file.FullPath);
            }
            CreateZip(selectedFilePaths);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
}
Private Async Sub OnSelectFilesButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
	Try
		Dim status = Await Permissions.RequestAsync(Of Permissions.StorageRead)()
		If status <> PermissionStatus.Granted Then
			Await DisplayAlert("Alert!", "Storage Access Denied", "Ok")
			Return
		End If
		' Select Multiple files of any type
		Dim results = Await FilePicker.PickMultipleAsync()
		If results IsNot Nothing Then
			Dim selectedFilePaths = New List(Of String)()
			For Each file In results
				' Add File Full Path to the list one by one
				selectedFilePaths.Add(file.FullPath)
			Next file
			CreateZip(selectedFilePaths)
		End If
	Catch ex As Exception
		Console.WriteLine($"Error: {ex.Message}")
	End Try
End Sub
VB   C#

Now, let's implement the CreateZip method, where IronZIP's IronArchive class takes the path of the zip filename to be created. Looping through each selected file path, it is added to the zip file by the Add method.

When the files are added, a confirmation message is displayed using DisplayAlert.

private async void CreateZip(List<string> selectedFilePaths)
{
    var path = "E:\\output.zip";
    // Create a Zip
    using (var archive = new IronArchive(path))
    {
        // Add files to the ZIP
        foreach (var file in selectedFilePaths)
        {
            archive.Add(file);
        }
    }
    await DisplayAlert("Congratulations", "All files add to the " + path, "Ok");
}
private async void CreateZip(List<string> selectedFilePaths)
{
    var path = "E:\\output.zip";
    // Create a Zip
    using (var archive = new IronArchive(path))
    {
        // Add files to the ZIP
        foreach (var file in selectedFilePaths)
        {
            archive.Add(file);
        }
    }
    await DisplayAlert("Congratulations", "All files add to the " + path, "Ok");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

For more detailed information on how to create, add files to existing zip and extract zip, please visit this tutorial page.

2. Extract zip

Now, we'll create the "Extract Zip" functionality. Again, in the MainPage.xaml.cs file, implement the OnSelectFileButtonClicked method to allow opening the FilePicker and selecting a single zip file for extraction.

The selected file's full path is set to a string variable and sent to the ExtractZip method where IronZIP performs extraction. The code goes as follows:

private async void OnSelectFileButtonClicked(object sender, EventArgs e)
{
    try
    {
        var status = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Alert!", "Storage Access Denied", "Ok");
            return;
        }
        // Select Multiple files of any type
        var result = await FilePicker.PickAsync();
        if (result != null)
        {
            // Add File Full Path to the list one by one
            var selectedFile = result.FullPath;
            ExtractZip(selectedFile);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
}
private async void OnSelectFileButtonClicked(object sender, EventArgs e)
{
    try
    {
        var status = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Alert!", "Storage Access Denied", "Ok");
            return;
        }
        // Select Multiple files of any type
        var result = await FilePicker.PickAsync();
        if (result != null)
        {
            // Add File Full Path to the list one by one
            var selectedFile = result.FullPath;
            ExtractZip(selectedFile);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
}
Private Async Sub OnSelectFileButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
	Try
		Dim status = Await Permissions.RequestAsync(Of Permissions.StorageRead)()
		If status <> PermissionStatus.Granted Then
			Await DisplayAlert("Alert!", "Storage Access Denied", "Ok")
			Return
		End If
		' Select Multiple files of any type
		Dim result = Await FilePicker.PickAsync()
		If result IsNot Nothing Then
			' Add File Full Path to the list one by one
			Dim selectedFile = result.FullPath
			ExtractZip(selectedFile)
		End If
	Catch ex As Exception
		Console.WriteLine($"Error: {ex.Message}")
	End Try
End Sub
VB   C#

Now, let's create the ExtractZip method. In this method, set the path to the output folder where you want to extract the files.

Using IronZIP's ExtractArchiveToDirectory method, pass the selected file path and output path. This method seamlessly converts and transfers all the files in the zip to the output folder. Finally, a confirmation message is shown on successful extraction.

The code goes as follows:

private async void ExtractZip(string selectedFilePath)
{
    var path = "E:\\Extracted Files";
    IronArchive.ExtractArchiveToDirectory(selectedFilePath, path);
    await DisplayAlert("Congratulations", "All files extracted to the " + path, "Ok");
}
private async void ExtractZip(string selectedFilePath)
{
    var path = "E:\\Extracted Files";
    IronArchive.ExtractArchiveToDirectory(selectedFilePath, path);
    await DisplayAlert("Congratulations", "All files extracted to the " + path, "Ok");
}
Private Async Sub ExtractZip(ByVal selectedFilePath As String)
	Dim path = "E:\Extracted Files"
	IronArchive.ExtractArchiveToDirectory(selectedFilePath, path)
	Await DisplayAlert("Congratulations", "All files extracted to the " & path, "Ok")
End Sub
VB   C#

Step 3 Run Application

After successfully integrating the code along with IronZIP, build and run the application to perform data extraction tasks. Test the functionality by creating a zip file and extracting files from a zip file.

Verify the results by checking the output and extracted files in the specified directories.

Step 4 Verify Results

1. Testing Create Zip

Let's first try to create a zip file. Click on the Create Zip button and it will present you with a file dialog. You can choose multiple or a single file to add to the zip.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 8

Click Open and a confirmation message will appear that the files have been successfully added to output.zip.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 9

If we navigate to the output.zip file and view its contents, we'll see all the files that we added.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 10

2. Testing Extract Zip

Let's now extract a zip file. Click on the Extract Zip button and a File dialog will appear. Choose a zip file that you want to extract and click open.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 11

Once the data capture from the zip file is done and extracted to the desired folder, it shows the confirmation message.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 12

Now, navigate to the "Extracted Files" folder and you'll see the files extracted from the zip we chose.

.NET MAUI Data Extraction SDK (Developer Tutorial): Figure 13

Conclusion

In conclusion, integrating IronZIP with .NET MAUI provides a powerful solution for creating, reading, and extracting archives in cross-platform applications.

The provided example demonstrates how to use IronZIP for selecting multiple files, generating a zip archive, and extracting files from a zip archive within .NET MAUI.

This combination of technologies offers developers a seamless experience in managing and manipulating archives across various platforms.

For more detailed information and code examples, please visit this documentation page.

IronZIP offers a free trial. You can download the library from here and give it a try.

< PREVIOUS
.NET ZipArchive (Developer Tutorial)
NEXT >
How to Create Zip Archive in C#

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 5,153 View Licenses >