Costruire un ZIP in memoria è utile quando è necessario trasmettere un download, passare i byti a un altro servizio, o memorizzare un archivio in una banca dati senza toccare il disco. Aspose.ZIP per .NET esprime un’API pulita per creare archivi zIP utilizzando i flussi, selezionare le impostazioni di compressione e salvare il risultato in un MemoryStream o direttamente alla risposta HTTP.

Questa guida fornisce il codice completo e corretto che puoi inserire in un’app di console o nel progetto ASP.NET Core.

Prerequisiti

  • .NET 6 o successivo
  • di NuGet: Aspose.Zip
dotnet add package Aspose.Zip

I nomi utilizzati:

using Aspose.Zip;                 // Archive, ArchiveEntry
using Aspose.Zip.Saving;          // DeflateCompressionSettings, CompressionLevel

Inizio rapido: creare un ZIP completamente nella memoria

Questo esempio aggiunge le entrate da una riga e un file sul disco, salva l’archivio in un MemoryStream, e esprime il risultato byte array.

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

class Program
{
    static void Main()
    {
        // Prepare output buffer
        using var zipBuffer = new MemoryStream();

        // Choose compression (Deflate is the standard ZIP method)
        var deflate = new DeflateCompressionSettings(CompressionLevel.Normal);
        var entrySettings = new ArchiveEntrySettings(deflate);

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

            // 2) Add a file from disk (streamed; not fully loaded in RAM)
            var sourcePath = "report.pdf"; // ensure it exists
            if (File.Exists(sourcePath))
            {
                using var fs = File.OpenRead(sourcePath);
                archive.CreateEntry("reports/2025/report.pdf", fs, entrySettings);
            }

            // 3) Save the ZIP to our in-memory buffer
            archive.Save(zipBuffer);
        }

        // Use the ZIP bytes as needed (send over network, write to DB, etc.)
        byte[] zipBytes = zipBuffer.ToArray();
        Console.WriteLine($"ZIP size: {zipBytes.Length} bytes");
    }
}
  • punti chiave *
  • new Archive() Crea un ZIP vuoto.
  • CreateEntry(entryName, stream, entrySettings) Aggiunge un file da ogni flusso leggibile.
  • archive.Save(stream) scrive l’archivio al tuo flusso scelto (memoria, rete, corpo di risposta).

Aggiungi un intero foglio di cartella senza scrivere file temp

Passare un directory recursivamente, conservare i percorsi relativi, e scrivere l’archivio finale nella memoria.

using System.IO;
using Aspose.Zip;
using Aspose.Zip.Saving;

static class InMemoryZipper
{
    public static byte[] ZipFolderToBytes(string sourceFolder, CompressionLevel level = CompressionLevel.Normal)
    {
        if (!Directory.Exists(sourceFolder))
            throw new DirectoryNotFoundException(sourceFolder);

        var deflate = new DeflateCompressionSettings(level);
        var entrySettings = new ArchiveEntrySettings(deflate);

        using var buffer = new MemoryStream();
        using (var archive = new Archive())
        {
            var root = Path.GetFullPath(sourceFolder);
            foreach (var filePath in Directory.GetFiles(root, "*", SearchOption.AllDirectories))
            {
                var rel = Path.GetRelativePath(root, filePath).Replace(Path.DirectorySeparatorChar, '/');
                using var fs = File.OpenRead(filePath);
                archive.CreateEntry(rel, fs, entrySettings);
            }

            archive.Save(buffer);
        }
        return buffer.ToArray();
    }
}

ASP.NET Core: trasmettere un download ZIP senza disco I/O

Questo punto finale costruisce un ZIP nella memoria da più fonti e lo restituisce con il tipo di contenuto corretto e un nome di file scaricato.

// File: Program.cs (minimal API)
using System.Text;
using Aspose.Zip;
using Aspose.Zip.Saving;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/download-zip", () =>
{
    using var buffer = new MemoryStream();
    var deflate = new DeflateCompressionSettings(CompressionLevel.Normal);
    var settings = new ArchiveEntrySettings(deflate);

    using (var archive = new Archive())
    {
        // Add dynamic content (for example, a CSV generated on the fly)
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("id,name\n1,Alice\n2,Bob\n")))
            archive.CreateEntry("data/users.csv", ms, settings);

        // Add a static file from disk if available
        var logo = "wwwroot/logo.png";
        if (File.Exists(logo))
        {
            using var fs = File.OpenRead(logo);
            archive.CreateEntry("assets/logo.png", fs, settings);
        }

        archive.Save(buffer);
    }

    buffer.Position = 0; // rewind for reading
    return Results.File(
        fileContents: buffer.ToArray(),
        contentType: "application/zip",
        fileDownloadName: $"bundle-{DateTime.UtcNow:yyyyMMdd-HHmmss}.zip");
});

app.Run();
  • Perché si tratta di un’indagine qui? *Le API minime richiedono un carico di pagamento concreto. per archivi molto grandi, si preferisce streaming direttamente a HttpResponse.Body:
app.MapGet("/stream-zip", async (HttpContext ctx) =>
{
    ctx.Response.ContentType = "application/zip";
    ctx.Response.Headers.ContentDisposition = $"attachment; filename=\"bundle.zip\"";

    var deflate = new DeflateCompressionSettings(CompressionLevel.Normal);
    var settings = new ArchiveEntrySettings(deflate);

    using var archive = new Archive();

    // Add entries...
    using var ms = new MemoryStream(Encoding.UTF8.GetBytes("hello"));
    archive.CreateEntry("hello.txt", ms, settings);

    // Stream directly to the client without buffering full ZIP in RAM
    await archive.SaveAsync(ctx.Response.Body);
});

Scegli le impostazioni di compressione

DeflateCompressionSettings Controllo velocità vs dimensioni:

var fastest = new DeflateCompressionSettings(CompressionLevel.Low);      // fastest, larger files
var balanced = new DeflateCompressionSettings(CompressionLevel.Normal);  // default balance
var smallest = new DeflateCompressionSettings(CompressionLevel.High);    // slowest, smallest files

Passare le impostazioni tramite new ArchiveEntrySettings(deflate) quando si creano le entrate. si possono mescolare le impostazioni per entrata se necessario.

Aggiungi le entrate dai flussi in modo sicuro

  • Utilizzo File.OpenRead(path) per trasmettere file di grandi dimensioni senza caricarli completamente nella memoria.
  • Per il contenuto generato, scrivere a MemoryStream o a PipeWriter-sostenere il flusso e trasmetterlo a CreateEntry.
  • Dispone di flussi dopo ciascuno CreateEntry Rilasciare rapidamente le risorse.

Un esempio di contenuti generati:

using System.IO;
using Aspose.Zip;
using Aspose.Zip.Saving;

static void AddLargeGeneratedEntry(Archive archive, string name)
{
    // simulate a big stream produced incrementally
    using var temp = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 81920, FileOptions.DeleteOnClose);
    using var writer = new StreamWriter(temp);
    for (int i = 0; i < 200_000; i++) writer.WriteLine($"row-{i},value-{i}");
    writer.Flush();
    temp.Position = 0;

    var settings = new ArchiveEntrySettings(new DeflateCompressionSettings(CompressionLevel.Normal));
    archive.CreateEntry(name, temp, settings);
}

Validazione e errore di gestione

  • Verificare gli input esistenti prima di aggiungere all’archivio.
  • La creazione in try/catch e restituire un chiaro errore HTTP per le API web.
  • Ristrutturazione delle strade di ingresso con gli spostamenti avanti (/per un comportamento coerente attraverso gli strumenti.

Checklist di prestazioni

  • Choose CompressionLevel.Low per i download in tempo reale quando la velocità è più importante della dimensione.
  • Evitare il carico di ingressi massicci completamente in RAM; flusso da file o flussi di rete.
  • Per archivi multi-GB molto grandi, trasmettere direttamente a HttpResponse.Body o un altro flusso target invece di buffering.
  • Dispose Archive e tutti gli input fluttuano deterministicamente.

FAQ

** Posso proteggere la password in-memory ZIP?**Aspose.ZIP supporta archivi ZIP crittografati. TraditionalEncryptionSettings o AesEncryptionSettings via ArchiveEntrySettingsApplicare per ingresso quando si chiama CreateEntry.

** Posso aggiornare un ZIP esistente che ho caricato nella memoria?**Sì, lo scarica in una Archive, aggiungere o rimuovere le entrate, quindi Save Torna a un flusso.

** Questo funziona nel Servizio Azure App o nei contenitori?**In-memory e streaming zipping funziona bene in ambienti sandboxed dove l’accesso al disco è limitato.

Il riassunto

Ha creato un archivio ZIP interamente in memoria con Aspose.ZIP per .NET, ha aggiunto le entrate dai flussi, la compressione adeguata e ha restituito l’archivo da un punto di fine ASP.NET Core senza file temporanei. Utilizzare questi modelli per generare download, pacchetti e esportazioni in modo efficiente nelle applicazioni C#.

More in this category