Passer au contenu du pied de page
UTILISER IRONZIP

SDK d'Extraction de Données .NET MAUI avec IronZIP

.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 other devices. Similar to React Native, but it uses C# instead of JavaScript.

.NET MAUI allows C# developers to build hassle-free mobile applications and desktop apps from a single environment. Microsoft .NET MAUI provides comprehensive documentation and resources to help developers streamline 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 the C# Zip Library using NuGet
  3. Design the 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, with everything 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 App's 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 provide 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 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
$vbLabelText   $csharpLabel

Next, implement the CreateZip method. IronZIP's IronArchive class takes the path where the zip file is to be created. Looping through each selected file path, they're 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 added to " + 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 added to " + path, "Ok");
}
Private Async Sub CreateZip(ByVal selectedFilePaths As List(Of String))
	Dim path = "E:\output.zip"
	' Create a Zip
	Using archive = New IronArchive(path)
		' Add files to the ZIP
		For Each file In selectedFilePaths
			archive.Add(file)
		Next file
	End Using
	Await DisplayAlert("Congratulations", "All files added to " & path, "Ok")
End Sub
$vbLabelText   $csharpLabel

For more detailed information on how to create, add files to existing zip, and extract a 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 the 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 a single file 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 a single file 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 a single file 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
$vbLabelText   $csharpLabel

Next, 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 " + path, "Ok");
}
private async void ExtractZip(string selectedFilePath)
{
    var path = "E:\\Extracted Files";
    IronArchive.ExtractArchiveToDirectory(selectedFilePath, path);
    await DisplayAlert("Congratulations", "All files extracted to " + 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 " & path, "Ok")
End Sub
$vbLabelText   $csharpLabel

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.

Questions Fréquemment Posées

Comment puis-je intégrer une bibliothèque ZIP à un projet .NET MAUI ?

Pour intégrer une bibliothèque ZIP comme IronZIP à un projet .NET MAUI, créez un nouveau projet .NET MAUI dans Visual Studio, installez la bibliothèque IronZIP via NuGet, et implémentez les fonctionnalités des archives ZIP en utilisant des exemples de code fournis.

Quels sont les avantages d'utiliser une bibliothèque ZIP dans une application .NET MAUI ?

L'utilisation d'une bibliothèque ZIP comme IronZIP dans une application .NET MAUI permet une compression et une extraction de données efficaces, prend en charge plusieurs formats d'archives, et est compatible sur diverses plateformes et versions de .NET.

Puis-je utiliser une bibliothèque ZIP pour des applications multiplateformes ?

Oui, vous pouvez utiliser IronZIP pour des applications multiplateformes. Il prend en charge les applications C#, F#, et VB.NET sur Windows, Linux, Mac, iOS, et Android.

Comment créer un fichier ZIP dans une application .NET MAUI ?

Dans une application .NET MAUI, vous pouvez créer un fichier ZIP en utilisant la bibliothèque IronZIP. Implémentez la méthode OnSelectFilesButtonClicked pour permettre la sélection de fichiers, et utilisez la classe IronArchive pour ajouter des fichiers à une archive ZIP avec la méthode CreateZip.

Comment puis-je extraire des fichiers d'une archive ZIP dans un projet .NET MAUI ?

Pour extraire des fichiers d'une archive ZIP dans un projet .NET MAUI, utilisez la méthode ExtractArchiveToDirectory de IronZIP. Tout d'abord, implémentez la méthode OnSelectFileButtonClicked pour sélectionner un fichier ZIP, puis extrayez son contenu dans un répertoire spécifié.

Quels formats d'archives IronZIP prend-il en charge ?

IronZIP prend en charge une variété de formats d'archives, notamment ZIP, TAR, GZIP, et BZIP2, ce qui en fait un choix polyvalent pour gérer différents types d'archives de fichiers compressés.

IronZIP est-il compatible avec différentes versions de .NET ?

Oui, IronZIP est compatible avec diverses versions de .NET, telles que .NET 7, 6, 5, Core, Standard, et Framework, offrant de la flexibilité aux développeurs travaillant avec différents environnements .NET.

Quelles sont les conditions préalables à l'implémentation d'une bibliothèque ZIP dans .NET MAUI ?

Pour implémenter une bibliothèque ZIP comme IronZIP dans .NET MAUI, assurez-vous d'avoir Visual Studio avec la charge de travail .NET MAUI installée, et que la bibliothèque IronZIP est ajoutée à votre projet via NuGet.

Comment puis-je améliorer une application .NET MAUI avec des fonctionnalités ZIP ?

Améliorez une application .NET MAUI en intégrant IronZIP pour gérer la création et l'extraction de fichiers ZIP, offrant aux utilisateurs des capacités robustes de compression et de décompression des données.

Où puis-je trouver plus d'informations sur l'utilisation des bibliothèques ZIP dans .NET MAUI ?

Pour plus d'informations détaillées et d'exemples de code, vous pouvez visiter la page de documentation de IronZIP, qui offre des instructions complètes sur l'intégration et l'utilisation des fonctionnalités ZIP dans les projets .NET MAUI.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite