El formato 7z es una elección popular para la compresión y distribución de alto índice. con Aspose.ZIP para .NET, se pueden crear archivos 7Z de manera programática utilizando una simple API moderna. Este guía pasa a través de un ejemplo de trabajo mínimo y añade patrones prácticos para proyectos reales, tales como agregar ficheros desde el disco, transmitir datos de la memoria, controlar los nombres de entrada y las cartas dentro del archivo, y el manejo de errores básicos.

Todas las muestras de código son inline y autónomas.

Prerequisitos

  • .NET 6 o más tarde
  • NuGet paquete Aspose.Zip
dotnet add package Aspose.Zip

Nombres utilizados en las muestras:Aspose.Zip, Aspose.Zip.SevenZip

Inicio rápido: crear un archivo 7z con unos pocos archivos

Este ejemplo mínimo crea un nuevo archivo de 7z en la memoria, añade dos entradas y lo salva en el disco.

// File: Program.cs
using System;
using System.IO;
using System.Text;
using Aspose.Zip.SevenZip;

class Program
{
    static void Main()
    {
        var outputPath = "example.7z";

        using (var archive = new SevenZipArchive())
        {
            // Add a text file from memory
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("Hello 7z from Aspose.ZIP")))
            {
                archive.CreateEntry("docs/readme.txt", ms);
            }

            // Add a file from disk
            var sourceFile = "report.pdf"; // ensure this file exists
            if (File.Exists(sourceFile))
            {
                using var fs = File.OpenRead(sourceFile);
                archive.CreateEntry("reports/2025/report.pdf", fs);
            }

            // Save the 7z archive
            using var outStream = File.Create(outputPath);
            archive.Save(outStream);
        }

        Console.WriteLine("Saved 7z: " + Path.GetFullPath(outputPath));
    }
}
  • Lo que hay que notar*
  • SevenZipArchive empieza vacío, luego llaman CreateEntry(entryName, stream) por elemento.
  • Los nombres de entrada definen la estructura de la carpeta dentro del archivo, como: docs/readme.txt.
  • Puedes pasar cualquier lectura Stream, que es útil para los datos que genera en la memoria.

Agregar un árbol completo

Caminar un directorio de forma recurrente, preservar su estructura relativa dentro del archivo, y guardar como .7z.

using System;
using System.IO;
using Aspose.Zip.SevenZip;

static class FolderTo7z
{
    public static void CreateFromFolder(string sourceDir, string output7z)
    {
        if (!Directory.Exists(sourceDir))
            throw new DirectoryNotFoundException(sourceDir);

        using var archive = new SevenZipArchive();

        var basePath = Path.GetFullPath(sourceDir);
        foreach (var filePath in Directory.GetFiles(basePath, "*", SearchOption.AllDirectories))
        {
            var relPath = Path.GetRelativePath(basePath, filePath)
                              .Replace(Path.DirectorySeparatorChar, '/'); // normalize to forward slashes

            using var fs = File.OpenRead(filePath);
            archive.CreateEntry(relPath, fs);
        }

        using var outStream = File.Create(output7z);
        archive.Save(outStream);
    }
}

// Usage
// FolderTo7z.CreateFromFolder(@"C:\data\input", "bundle.7z");
  • Título *
  • Uso Path.GetRelativePath para mantener el layout interno de la carpeta limpio.
  • Normalizar los separadores de ruta para avanzar los rasgos para las entradas de archivo consistentes.

Flujo de archivos grandes de forma segura

Al añadir grandes archivos, fluye en lugar de buffar todo el archivo en la memoria. File.OpenRead Si genera contenido en el avión, escriba en un Stream y pasar ese flujo directamente a CreateEntry.

using System.IO;
using System.Text;
using Aspose.Zip.SevenZip;

static void AddGeneratedCsv(SevenZipArchive archive, string entryName)
{
    // Example generator that writes CSV rows in a forward-only fashion
    using var pipe = new MemoryStream();
    using var writer = new StreamWriter(pipe, Encoding.UTF8, leaveOpen: true);

    writer.WriteLine("id,name");
    for (int i = 1; i <= 1000; i++)
        writer.WriteLine($"{i},Item {i}");

    writer.Flush();
    pipe.Position = 0;

    archive.CreateEntry(entryName, pipe);
}

Organizar las entradas con un ayudante

Para trabajos más grandes, use un pequeño ayudante para agregar archivos con un prefixo común. Esto mantiene su estructura de archivo predictable.

using System.IO;
using Aspose.Zip.SevenZip;

static class SevenZipHelpers
{
    public static void AddFile(SevenZipArchive archive, string rootPrefix, string fullPath)
    {
        var relName = Path.Combine(rootPrefix, Path.GetFileName(fullPath))
                           .Replace(Path.DirectorySeparatorChar, '/');
        using var fs = File.OpenRead(fullPath);
        archive.CreateEntry(relName, fs);
    }
}

Ejemplo de fin a fin con logging y controles básicos

Este ejemplo crea un archivo de 7z de una lista mixta de fuentes. Valida los pasos y logs resultados.

// File: BuildArchive.cs
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Zip.SevenZip;

public static class BuildArchive
{
    public static bool Run(IEnumerable<string> paths, string output7z)
    {
        if (paths == null) throw new ArgumentNullException(nameof(paths));
        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output7z)) ?? ".");

        int added = 0, skipped = 0;

        using var archive = new SevenZipArchive();

        foreach (var p in paths)
        {
            if (string.IsNullOrWhiteSpace(p)) { skipped++; continue; }

            if (File.Exists(p))
            {
                using var fs = File.OpenRead(p);
                var entryName = Path.GetFileName(p);
                archive.CreateEntry(entryName, fs);
                Console.WriteLine("Added file: " + entryName);
                added++;
            }
            else if (Directory.Exists(p))
            {
                var basePath = Path.GetFullPath(p);
                foreach (var fp in Directory.GetFiles(basePath, "*", SearchOption.AllDirectories))
                {
                    var rel = Path.GetRelativePath(basePath, fp).Replace(Path.DirectorySeparatorChar, '/');
                    using var fs = File.OpenRead(fp);
                    archive.CreateEntry(rel, fs);
                    Console.WriteLine("Added: " + rel);
                    added++;
                }
            }
            else
            {
                Console.WriteLine("Skip missing: " + p);
                skipped++;
            }
        }

        using var outStream = File.Create(output7z);
        archive.Save(outStream);

        Console.WriteLine($"Saved: {Path.GetFullPath(output7z)}");
        Console.WriteLine($"Entries added: {added}, skipped: {skipped}");
        return added > 0;
    }
}

// Usage sample:
// BuildArchive.Run(new [] { "README.md", "assets", "docs/spec.pdf" }, "release.7z");

Las mejores prácticas

  • Use adelante para los nombres de entradaMuchas herramientas muestran los caminos más consistentemente cuando las entradas se utilizan / como el separador.

    • Dispone de flujos*Siempre incorporar los flujos de archivos en using Las muestras de arriba garantizan una limpieza.
    • Validación de las entradas*Verifique que los archivos existen antes de agregarlos. proporcionar logs claros para los caminos desplazados.
    • Mantener la estructura del archivo limpia*Decide sobre un nombre de la carpeta de raíz dentro del archivo y adhiere a él, como app/ o package/.
  • Test en las plataformas de destinoAsegúrese de que su 7z se abre correctamente en las herramientas que sus usuarios dependen.

Resumen

Creó un archivo de 7z de manera programática con Aspose.ZIP para .NET, añadió archivos desde el disco y la memoria, conservó una estructura de carpeta limpia, y salvó el resultado para .7zUtilice estos patrones para emisiones de paquete, paquetes y exportaciones directamente de sus aplicaciones C#.

More in this category