How to create and fill a ZIP file using ASP.NET?

后端 未结 9 1777
暖寄归人
暖寄归人 2020-12-14 17:29

Need to dynamically package some files into a .zip to create a SCORM package, anyone know how this can be done using code? Is it possible to build the folder structure dynam

相关标签:
9条回答
  • 2020-12-14 17:38

    If you're using .NET Framework 4.5 or newer you can avoid third-party libraries and use the System.IO.Compression.ZipArchive native class.

    Here’s a quick code sample using a MemoryStream and a couple of byte arrays representing two files:

    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");
    }
    

    You can use it inside a MVC Controller returning an ActionResult: alternatively, if you need to phisically create the zip archive, you can either persist the MemoryStream to disk or entirely replace it with a FileStream.

    For further info regarding this topic you can also read this post on my blog.

    0 讨论(0)
  • 2020-12-14 17:42

    Creating ZIP file "on the fly" would be done using our Rebex ZIP component.

    The following sample describes it fully, including creating a subfolder:

    // 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();
    
    0 讨论(0)
  • 2020-12-14 17:45

    I have used a free component from chilkat for this: http://www.chilkatsoft.com/zip-dotnet.asp. Does pretty much everything I have needed however I am not sure about building the file structure dynamically.

    0 讨论(0)
  • 2020-12-14 17:46
    #region Create zip file in asp.net c#
            string DocPath1 = null;/*This varialble is Used for Craetting  the File path .*/
            DocPath1 = Server.MapPath("~/MYPDF/") + ddlCode.SelectedValue + "/" + txtYear.Value + "/" + ddlMonth.SelectedValue + "/";
            string[] Filenames1 = Directory.GetFiles(DocPath1);
            using (ZipFile zip = new ZipFile())
            {
                zip.AddFiles(Filenames, "Pdf");//Zip file inside filename
                Response.Clear();
                Response.BufferOutput = false;
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(Response.OutputStream);
                Response.End();
            }
            #endregion
    
    0 讨论(0)
  • 2020-12-14 17:51

    Able to do this using DotNetZip. you can download it from the visual studio Nuget package manger or directly via the DotnetZip. then try below code,

         /// <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");
            }
        }
    

    If you want to download the file into client,use below code.

    /// <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();
        }
    
    0 讨论(0)
  • 2020-12-14 17:54

    DotNetZip is very easy to use... Creating Zip files in ASP.Net

    0 讨论(0)
提交回复
热议问题