跳過到頁腳內容
使用 IRONZIP

.NET MAUI 數據提取 SDK 與 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.

常見問題解答

如何將 ZIP 庫整合到 .NET MAUI 專案中?

要將像 IronZIP 這樣的 ZIP 庫整合到 .NET MAUI 項目中,可以在 Visual Studio 中創建一個新的 .NET MAUI 項目,通過 NuGet 安裝 IronZIP 庫,並使用提供的代碼範例實現 ZIP 壓縮功能。

在 .NET MAUI 應用中使用 ZIP 庫有何好處?

在 .NET MAUI 應用中使用像 IronZIP 這樣的 ZIP 庫,可以提高數據壓縮和提取的效率,支持多種壓縮格式,並且與各種平台和 .NET 版本兼容。

我可以將 ZIP 庫用於跨平台應用嗎?

是的,您可以將 IronZIP 用於跨平台應用。它支持在 Windows、Linux、Mac、iOS 和 Android 上使用 C#、F# 和 VB.NET 應用程序。

如何在 .NET MAUI 應用中創建 ZIP 文件?

在 .NET MAUI 應用中,可以使用 IronZIP 庫創建 ZIP 文件。實現 OnSelectFilesButtonClicked 方法以允許文件選擇,並使用 IronArchive 類將文件添加到 ZIP 存檔中,並使用 CreateZip 方法進行創建。

如何在 .NET MAUI 項目中從 ZIP 存檔中提取文件?

要在 .NET MAUI 項目中從 ZIP 存檔中提取文件,可使用 IronZIP 的 ExtractArchiveToDirectory 方法。首先,實現 OnSelectFileButtonClicked 方法選擇 ZIP 文件,然後將其內容提取到指定目錄。

IronZIP 支持哪些存檔格式?

IronZIP 支持多種存檔格式,包括 ZIP、TAR、GZIP 和 BZIP2,使其成為處理不同類型壓縮檔案的靈活選擇。

IronZIP 兼容不同的 .NET 版本吗?

是的,IronZIP 與各種 .NET 版本兼容,如 .NET 7、6、5、Core、Standard 和 Framework,提供了為不同 .NET 環境工作的開發人員靈活性。

在 .NET MAUI 中實現 ZIP 庫的先決條件有哪些?

要在 .NET MAUI 中實現像 IronZIP 這樣的 ZIP 庫,請確保您已安裝帶有 .NET MAUI 工作負載的 Visual Studio,並且已通過 NuGet 將 IronZIP 庫添加到項目中。

如何增強 .NET MAUI 應用的 ZIP 功能?

通過整合 IronZIP 以管理 ZIP 文件的創建和提取,增強 .NET MAUI 應用,為用戶提供強大的數據壓縮和解壓能力。

在哪裡可以找到更多關於在 .NET MAUI 中使用 ZIP 庫的信息?

有關更多詳細信息和代碼示例,您可以訪問 IronZIP 檔案頁面,該頁提供了有關整合和使用在 .NET MAUI 項目中 ZIP 功能的全面指導。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。