Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Use System.IO.Compression in Windows to Manage Zip Files

System.IO.Compression is a namespace in the .NET framework that provides classes for compressing and decompressing streams. This is particularly useful for managing zip files, which is a common task in both development and system administration. In a Windows environment, leveraging System.IO.Compression can streamline tasks such as packaging files for distribution, reducing storage space, and transferring files over the network.

In this article, we will explore how to use System.IO.Compression to create and extract zip files using C# and PowerShell. We will provide practical examples to illustrate these tasks, ensuring that even those new to the topic can follow along.

Examples:

Example 1: Creating a Zip File Using C

To create a zip file in C#, you can use the ZipFile class from the System.IO.Compression namespace. Below is a sample code snippet that demonstrates how to zip a directory.

using System;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        string sourceDirectory = @"C:\Example\Source";
        string zipPath = @"C:\Example\result.zip";

        ZipFile.CreateFromDirectory(sourceDirectory, zipPath);

        Console.WriteLine("Directory zipped successfully!");
    }
}

Example 2: Extracting a Zip File Using C

To extract a zip file, you can use the ZipFile.ExtractToDirectory method. Here’s how you can do it:

using System;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        string zipPath = @"C:\Example\result.zip";
        string extractPath = @"C:\Example\Extracted";

        ZipFile.ExtractToDirectory(zipPath, extractPath);

        Console.WriteLine("Zip file extracted successfully!");
    }
}

Example 3: Creating a Zip File Using PowerShell

PowerShell provides a convenient way to create zip files using the Compress-Archive cmdlet. Here’s an example:

$sourceDirectory = "C:\Example\Source"
$zipPath = "C:\Example\result.zip"

Compress-Archive -Path $sourceDirectory -DestinationPath $zipPath

Write-Output "Directory zipped successfully!"

Example 4: Extracting a Zip File Using PowerShell

Similarly, you can extract a zip file using the Expand-Archive cmdlet in PowerShell:

$zipPath = "C:\Example\result.zip"
$extractPath = "C:\Example\Extracted"

Expand-Archive -Path $zipPath -DestinationPath $extractPath

Write-Output "Zip file extracted successfully!"

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.