Passer au contenu du pied de page
COMPARER à D'AUTRES COMPOSANTS

Tutoriel sur l'archivage zip pour les développeurs C# en utilisant IronXL

Introduction to ZipArchive

Whenever you think of sending a file over in a compressed format, the first thing that comes to mind is usually a Zip Archive. A zip archive is a popular format for compressing and packing a single file or an entire collection in a single archive. However, when there are large volumes of files to zip, working with them might become frustrating as you would have to archive and format them one by one. But it doesn't have to be like that. Large-volume tasks need automation to be done programmatically. We can use IronZip, a simple yet intuitive library, to achieve all that and more.

In this article, we'll briefly discuss IronZip's core features and functionalities and how it can help you better automate your workflow, increase efficiency, and eliminate error-prone manual tasks.

Creating a new zip file from a folder or files

Below is an example that takes in multiple files, zips them into one archive, and exports them after the operation. All examples in this article are encased in the static void Main() method to avoid repeated code blocks.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Create an empty ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Add files to the ZIP archive
            archive.Add("./assets/image1.jpg");
            archive.Add("./assets/image2.jpg");
            archive.Add("./assets/image3.jpg");

            // Export the ZIP archive to a file
            archive.SaveAs("output.zip");
        }
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Create an empty ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Add files to the ZIP archive
            archive.Add("./assets/image1.jpg");
            archive.Add("./assets/image2.jpg");
            archive.Add("./assets/image3.jpg");

            // Export the ZIP archive to a file
            archive.SaveAs("output.zip");
        }
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create an empty ZIP archive
		Using archive = New IronZipArchive()
			' Add files to the ZIP archive
			archive.Add("./assets/image1.jpg")
			archive.Add("./assets/image2.jpg")
			archive.Add("./assets/image3.jpg")

			' Export the ZIP archive to a file
			archive.SaveAs("output.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel
  1. We first import IronZip.
  2. Then, using IronZip, we create an archive.
  3. We call archive.Add() to add multiple files to the archive. Remember that path names must be absolute paths, or the operation will fail to find the corresponding files.
  4. Finally, we call archive.SaveAs() to export the zip archive as output.zip.

Updating an existing zip file with new files or modifications

Let's go over another example; this time, we will edit the existing zip archive with new files to showcase the functionality of IronZip.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive
        using (var archive = IronZipArchive.FromFile("existing.zip"))
        {
            // Add additional files to the existing ZIP archive
            archive.Add("./assets/image3.png");
            archive.Add("./assets/image4.png");

            // Export the updated ZIP archive to a new file
            archive.SaveAs("result.zip");
        }
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive
        using (var archive = IronZipArchive.FromFile("existing.zip"))
        {
            // Add additional files to the existing ZIP archive
            archive.Add("./assets/image3.png");
            archive.Add("./assets/image4.png");

            // Export the updated ZIP archive to a new file
            archive.SaveAs("result.zip");
        }
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Open an existing ZIP archive
		Using archive = IronZipArchive.FromFile("existing.zip")
			' Add additional files to the existing ZIP archive
			archive.Add("./assets/image3.png")
			archive.Add("./assets/image4.png")

			' Export the updated ZIP archive to a new file
			archive.SaveAs("result.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel
  1. We first import IronZip.
  2. Using IronZip, we create an archive, but this time, we import the existing zip file with IronZipArchive.FromFile().
  3. We call archive.Add() to add the desired files to the archive. Remember that path names must be absolute paths, or the operation will fail to find the existing files.
  4. Finally, we call archive.SaveAs() to export the updated zip archive as result.zip.

As you can see from the code above, the operation and format are similar to those used to create and add files to a Zip file. The main difference is that we import the zip file instead, showcasing IronZip's simple yet intuitive functionality.

Extracting files from a Zip archive

We can also use IronZip to extract files from a Zip archive or Zip package. Let's review this in another example.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract the ZIP archive content to a specified directory
        IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract the ZIP archive content to a specified directory
        IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract the ZIP archive content to a specified directory
		IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted")
	End Sub
End Class
$vbLabelText   $csharpLabel

We import IronZip and call IronZipArchive.ExtractArchiveToDirectory(). This method extracts the contents of the existing zip archive to the specified target directory.

Furthermore, in cases where you need to deal with password-protected zip archives, we can use another method to extract the archives.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract the protected ZIP archive content to a specified directory
        IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted", "P@ssw0rd");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract the protected ZIP archive content to a specified directory
        IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted", "P@ssw0rd");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract the protected ZIP archive content to a specified directory
		IronZipArchive.ExtractArchiveToDirectory("output.zip", "extracted", "P@ssw0rd")
	End Sub
End Class
$vbLabelText   $csharpLabel

Ultimately, we pass in another parameter: the password for the protected zip archive. The rest of the operation is the same as shown above.

Advanced Topics and Best Practices

The code examples for adding, extracting, and creating archives discussed above are the most common when dealing with zip archives. However, for more advanced usage, such as extracting other formats or simply viewing the archive's contents, IronZIP has you covered and more.

Advanced Features of IronZIP

  • Cross-compatibility: IronZIP is compatible with a wide range of .NET versions, including .NET Core (3.1+), Standard (2.0+), and .NET Framework (4.6.2+). The library also works on the Web (Blazor), Mobile (MAUI), Desktop (WPF), and Console. This allows developers to transcend platform and version limitations.

  • Generating Archives: Beyond the ZIP format, IronZIP supports creating TAR, GZIP, and BZIP2 archives.

  • Extracting Archives: Extract archives and decompress files easily with IronZIP using a single block of code, as demonstrated above.

  • Adding Files and File Systems: IronZIP assists in manipulating zip archives by adding images, text files, and documents (such as PDFs, DOCX, and XLSX), as well as audio files like MP3 and WAV. It can even compress entire file systems or individual text files into a ZipArchive archive.

  • Export and Create: You can password-protect archives with AES128 and AES256 standards. Additionally, you can generate and export formats like TAR, GZIP, and BZIP2.

  • Custom Compression Levels: IronZIP allows developers to adjust compression settings to fine-tune the algorithm to their needs.

  • Editing Archives: Easily add, extract, or delete file entries in an archive using IronZIP as a comprehensive solution for editing-related operations.

  • File Entry Properties: IronZIP provides the ability to set optional archive comments and retrieve file names within the archive without extracting them, aiding in leaving specific comments for each file.

  • Licensing Choices: IronZIP offers adaptable licensing choices, including complimentary trial versions, allowing developers to select what suits their requirements best.

Conclusion

Dealing with compressed files and archives is a daily task that developers often face, but managing a large volume of them can be stressful and prone to human error. Although there are options like System.IO.Compression, using IronZIP allows you to achieve more and quickly resolve issues when dealing with compressed archives. In this article, we discussed the advanced features of IronZIP and common operations like creating zip archives, deleting entries, or adding files. Understanding how to perform these tasks programmatically with IronZIP leads to increased efficiency, scalability, and automation in handling archives.

Veuillez noterSystem.IO.Compression is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by System.IO.Compression. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Questions Fréquemment Posées

Comment créer un fichier ZIP à partir d'un dossier en C# ?

Pour créer un fichier ZIP à partir d'un dossier en C#, vous pouvez utiliser la bibliothèque IronZip. Tout d'abord, importez la bibliothèque IronZip, créez une instance de IronZipArchive, ajoutez le dossier en utilisant archive.AddFolder(), et enregistrez-le avec archive.SaveAs().

Quel est le processus pour extraire des données d'une archive ZIP en C# ?

Vous pouvez extraire des données d'une archive ZIP en C# en utilisant IronZip en appelant la méthode IronZipArchive.ExtractArchiveToDirectory(). Cette méthode vous permet de spécifier un répertoire où le contenu sera extrait.

Comment puis-je mettre à jour le contenu d'une archive ZIP par programmation en C# ?

Pour mettre à jour le contenu d'une archive ZIP par programmation en C#, utilisez IronZip en chargeant l'archive existante avec IronZipArchive.FromFile(), puis utilisez archive.Add() pour ajouter des fichiers ou archive.Remove() pour supprimer des fichiers avant de sauvegarder les modifications avec archive.SaveAs().

IronZip peut-il gérer des fichiers ZIP protégés par mot de passe ?

Oui, IronZip peut gérer des fichiers ZIP protégés par mot de passe. Vous pouvez spécifier un mot de passe lors de l'extraction de fichiers en utilisant la méthode IronZipArchive.ExtractArchiveToDirectory() en fournissant le mot de passe comme paramètre supplémentaire.

Quels sont les avantages d'utiliser IronZip par rapport à System.IO.Compression pour la gestion des fichiers ZIP ?

IronZip offre des fonctionnalités avancées par rapport à System.IO.Compression telles que la prise en charge de plusieurs formats d'archives, la protection par mot de passe, des niveaux de compression personnalisés et la possibilité de modifier les archives en ajoutant ou supprimant des fichiers sans les extraire.

Comment IronZip assure-t-il la compatibilité croisée avec les différentes versions de .NET ?

IronZip assure la compatibilité croisée en supportant plusieurs versions de .NET, permettant aux développeurs d'intégrer la fonctionnalité de gestion des fichiers ZIP dans des applications fonctionnant sur différentes plateformes et frameworks.

Quelles fonctionnalités avancées offre IronZip pour la gestion des archives ZIP ?

IronZip offre des fonctionnalités avancées telles que la génération et l'extraction de plusieurs formats d'archives (ZIP, TAR, GZIP, BZIP2), la protection par mot de passe, des niveaux de compression personnalisés et des capacités d'édition complètes sans besoin d'extraire les fichiers.

Est-il possible de gérer les propriétés des fichiers au sein d'une archive ZIP en utilisant IronZip ?

Oui, IronZip vous permet de gérer les propriétés des fichiers telles que les commentaires au sein d'une archive ZIP sans besoin d'extraire d'abord les fichiers, améliorant la flexibilité et l'efficacité dans la gestion des archives.

Comment puis-je automatiser la création et l'extraction de fichiers ZIP en C# ?

Vous pouvez automatiser la création et l'extraction de fichiers ZIP en C# en utilisant IronZip dans une méthode static void Main(). Cela vous permet d'automatiser les processus tels que l'ajout de fichiers à une archive, l'extraction de données et la mise à jour de fichiers existants par programmation.

IronZip prend-il en charge la gestion de systèmes de fichiers entiers ?

Oui, IronZip prend en charge la compression et l'extraction de systèmes de fichiers entiers, ce qui le rend adapté pour traiter de grands volumes de données de manière efficace.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite