Как создать и заполнить ZIP-файл с помощью ASP.NET? - PullRequest
23 голосов
/ 25 марта 2009

Нужно динамически упаковать некоторые файлы в .zip для создания пакета SCORM, кто-нибудь знает, как это можно сделать с помощью кода? Можно ли динамически построить структуру папок внутри .zip?

Ответы [ 8 ]

21 голосов
/ 26 марта 2009

DotNetZip хорош для этого. Рабочий пример

Вы можете записать почтовый индекс непосредственно в Response.OutputStream. Код выглядит так:

    Response.Clear();
    Response.BufferOutput = false; // for large files...
    System.Web.HttpContext c= System.Web.HttpContext.Current;
    String ReadmeText= "Hello!\n\nThis is a README..." + DateTime.Now.ToString("G"); 
    string archiveName= String.Format("archive-{0}.zip", 
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); 
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "filename=" + archiveName);

    using (ZipFile zip = new ZipFile())
    {
        // filesToInclude is an IEnumerable<String>, like String[] or List<String>
        zip.AddFiles(filesToInclude, "files");            

        // Add a file from a string
        zip.AddEntry("Readme.txt", "", ReadmeText);
        zip.Save(Response.OutputStream);
    }
    // Response.End();  // no! See http://stackoverflow.com/questions/1087777
    Response.Close();

DotNetZip бесплатен.

15 голосов
/ 25 марта 2009

Вам больше не нужно использовать внешнюю библиотеку. System.IO.Packaging содержит классы, которые можно использовать для переноса содержимого в zip-файл. Это не просто, однако. Вот сообщение в блоге с примером (его в конце; копайте для него).


Ссылка не стабильна, поэтому вот пример, приведенный Джоном в посте.

using System;
using System.IO;
using System.IO.Packaging;

namespace ZipSample
{
    class Program
    {
        static void Main(string[] args)
        {
            AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe");
            AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe");
        }

        private const long BUFFER_SIZE = 4096;

        private static void AddFileToZip(string zipFilename, string fileToAdd)
        {
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                string destFilename = ".\\" + Path.GetFileName(fileToAdd);
                Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
                if (zip.PartExists(uri))
                {
                    zip.DeletePart(uri);
                }
                PackagePart part = zip.CreatePart(uri, "",CompressionOption.Normal);
                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                {
                    using (Stream dest = part.GetStream())
                    {
                        CopyStream(fileStream, dest);
                    }
                }
            }
        }

        private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
        {
            long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
            byte[] buffer = new byte[bufferSize];
            int bytesRead = 0;
            long bytesWritten = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                bytesWritten += bytesRead;
            }
        }
    }
}
7 голосов
/ 25 марта 2009

Вы можете взглянуть на SharpZipLib . А вот и образец .

3 голосов
/ 25 февраля 2011

DotNetZip очень прост в использовании ... Создание Zip-файлов в ASP.Net

1 голос
/ 12 апреля 2018

Возможность сделать это с помощью DotNetZip. Вы можете скачать его из менеджера пакетов Visual Studio Nuget или напрямую через DotnetZip . затем попробуйте следующий код,

     /// <summary>
    /// Generate zip file and save it into given location
    /// </summary>
    /// <param name="directoryPath"></param>
    public void CreateZipFile(string directoryPath )
    {
        //Select Files from given directory
        List<string> directoryFileNames = Directory.GetFiles(directoryPath).ToList();
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(directoryFileNames, "");
            //Generate zip file folder into loation
            zip.Save("C:\\Logs\\ReportsMyZipFile.zip");
        }
    }

Если вы хотите загрузить файл в клиент, используйте код ниже.

/// <summary>
    /// Generate zip file and download into client
    /// </summary>
    /// <param name="directoryPath"></param>
    /// <param name="respnse"></param>
    public void CreateZipFile(HttpResponse respnse,string directoryPath )
    {
        //Select Files from given directory
        List<string> directoryFileNames = Directory.GetFiles(directoryPath).ToList();
        respnse.Clear();
        respnse.BufferOutput = false;
        respnse.ContentType = "application/zip";
        respnse.AddHeader("content-disposition", "attachment; filename=MyFiles.zip");

        using (ZipFile zip = new ZipFile())
        {
            zip.CompressionLevel = CompressionLevel.None;
            zip.AddFiles(directoryFileNames, "");
            zip.Save(respnse.OutputStream);
        }

        respnse.flush();
    }
1 голос
/ 25 марта 2009

Я использовал для этого бесплатный компонент из chilkat: http://www.chilkatsoft.com/zip-dotnet.asp. Почти все, что мне нужно, однако я не уверен в динамическом построении файловой структуры.

0 голосов
/ 17 мая 2017

Если вы используете .NET Framework 4.5 или новее, вы можете избежать сторонних библиотек и использовать собственный класс System.IO.Compression.ZipArchive.

Вот краткий пример кода с использованием MemoryStream и парой байтовых массивов, представляющих два файла:

byte[] file1 = GetFile1ByteArray();
byte[] file2 = GetFile2ByteArray();

using (MemoryStream ms = new MemoryStream())
{
    using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        var zipArchiveEntry = archive.CreateEntry("file1.txt", CompressionLevel.Fastest);
        using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file1, 0, file1.Length);
        zipArchiveEntry = archive.CreateEntry("file2.txt", CompressionLevel.Fastest);
        using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file2, 0, file2.Length);
    }
    return File(ms.ToArray(), "application/zip", "Archive.zip");
}

Вы можете использовать его внутри контроллера MVC, возвращая ActionResult: альтернативно, если вам нужно физически создать zip-архив, вы можете либо сохранить MemoryStream на диске, либо полностью заменить его на FileStream.

Для получения дополнительной информации по этой теме вы также можете прочитать это сообщение в моем блоге.

0 голосов
/ 16 сентября 2010

Создание ZIP-файла "на лету" будет выполнено с использованием нашего Rebex ZIP компонента.

Следующий пример описывает это полностью, включая создание подпапки:

// prepare MemoryStream to create ZIP archive within
using (MemoryStream ms = new MemoryStream())
{
    // create new ZIP archive within prepared MemoryStream
    using (ZipArchive zip = new ZipArchive(ms))
    {            
         // add some files to ZIP archive
         zip.Add(@"c:\temp\testfile.txt");
         zip.Add(@"c:\temp\innerfile.txt", @"\subfolder");

         // clear response stream and set the response header and content type
         Response.Clear();
         Response.ContentType = "application/zip";
         Response.AddHeader("content-disposition", "filename=sample.zip");

         // write content of the MemoryStream (created ZIP archive) to the response stream
         ms.WriteTo(Response.OutputStream);
    }
}

// close the current HTTP response and stop executing this page
HttpContext.Current.ApplicationInstance.CompleteRequest();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...