Partha
Partha

Reputation: 2192

How to zip multiple files using only .net api in c#

I like to zip multiple files which are being created dynamically in my web application. Those files should be zipped. For this, i dont want to use any third-party tools. just like to use .net api in c#

Upvotes: 48

Views: 101454

Answers (8)

Marcom
Marcom

Reputation: 4751

Check out System.IO.Compression.DeflateStream. The linked documentation page also offers an example.

Upvotes: 0

Talha Hanjra
Talha Hanjra

Reputation: 410

Well you can zip the files using following function you have to just pass the file bytes and this function will zip the file bytes passed as parameter and return the zipped file bytes.

 public static byte[] PackageDocsAsZip(byte[] fileBytesTobeZipped, string packageFileName)
{
    try
    {
        string parentSourceLoc2Zip = @"C:\UploadedDocs\SG-ACA OCI Packages";
        if (Directory.Exists(parentSourceLoc2Zip) == false)
        {
            Directory.CreateDirectory(parentSourceLoc2Zip);
        }

        //if destination folder already exists then delete it
        string sourceLoc2Zip = string.Format(@"{0}\{1}", parentSourceLoc2Zip, packageFileName);
        if (Directory.Exists(sourceLoc2Zip) == true)
        {
            Directory.Delete(sourceLoc2Zip, true);
        }
        Directory.CreateDirectory(sourceLoc2Zip);

  

             FilePath = string.Format(@"{0}\{1}",
                    sourceLoc2Zip,
                    "filename.extension");//e-g report.xlsx , report.docx according to exported file

             File.WriteAllBytes(FilePath, fileBytesTobeZipped);




        //if zip already exists then delete it
        if (File.Exists(sourceLoc2Zip + ".zip"))
        {
            File.Delete(sourceLoc2Zip + ".zip");
        }

        //now zip the source location
        ZipFile.CreateFromDirectory(sourceLoc2Zip, sourceLoc2Zip + ".zip", System.IO.Compression.CompressionLevel.Optimal, true);

        return File.ReadAllBytes(sourceLoc2Zip + ".zip");
    }
    catch
    {
        throw;
    }
}

Now if you want to export this zip bytes created for user to download you can call this function using following lines

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.zip");
    Response.ContentType = "application/zip";
    Response.BinaryWrite(PackageDocsAsZip(fileBytesToBeExported ,"TemporaryFolderName"));
    Response.End();

Upvotes: 4

rjzii
rjzii

Reputation: 14563

With the release of the .NET Framework 4.5 this is actually a lot easier now with the updates to System.IO.Compression which adds the ZipFile class. There is a good walk-through on codeguru; however, the basics are in line with the following example:

using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.IO.Compression.FileSystem;

namespace ZipFileCreator
{
    public static class ZipFileCreator
    {
        /// <summary>
        /// Create a ZIP file of the files provided.
        /// </summary>
        /// <param name="fileName">The full path and name to store the ZIP file at.</param>
        /// <param name="files">The list of files to be added.</param>
        public static void CreateZipFile(string fileName, IEnumerable<string> files)
        {
            // Create and open a new ZIP file
            var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);
            foreach (var file in files)
            {
                // Add the entry for each file
                zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
            }
            // Dispose of the object when we are done
            zip.Dispose();
        }
    }
}

Upvotes: 60

Tomas Kubes
Tomas Kubes

Reputation: 25198

Simple zip file with flat structure:

using System.IO;
using System.IO.Compression;

private static void CreateZipFile(IEnumerable<FileInfo> files, string archiveName)
{
    using (var stream = File.OpenWrite(archiveName))
    using (ZipArchive archive = new ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create))
    {
         foreach (var item in files)
         {
             archive.CreateEntryFromFile(item.FullName, item.Name, CompressionLevel.Optimal);                       
         }
     }
}

You need to add reference to System.IO.Compression and System.IO.Compression.FileSystem

Upvotes: 10

The Pickle
The Pickle

Reputation: 125

DotNetZip is the way to go (dotnetzip.codeplex.com)... don't try the .NET Packaging library.. too hard to use and the [Content_Types].xml that it puts in there bothers me..

Upvotes: 0

cjk
cjk

Reputation: 46475

I'm not sure what you mean by not wanting to use thrid party tools, but I assume its that you don't want some nasty interop to programmatically do it through another piece of software.

I recommend using ICSharpCode SharpZipLib

This can be added to your project as a reference DLL and is fairly straightforward for creating ZIP files and reading them.

Upvotes: 5

ajs410
ajs410

Reputation: 2434

You could always call a third-party executable like 7-zip with an appropriate command line using the System.Diagnostics.Process class. There's no interop that way because you're just asking the OS to launch a binary.

Upvotes: 0

Related Questions