C# .NET - how to extract zip file using C# - Asked By Reshma Gurav on 27-Dec-11 07:20 AM

hello,

I want to extract zip file contents at specific location like C:/temp/...  using C#

how to do this??
dipa ahuja replied to Reshma Gurav on 27-Dec-11 07:20 AM
For zipping try this using shareZiplib:
 
 protected void Btn_Upload_Click(object sender, EventArgs e)
  {
  string folder = Server.MapPath("~/Files/");
  string filePath = FileUpload1.PostedFile.FileName;
  string fileName = System.IO.Path.GetFileName(filePath);
  FileUpload1.PostedFile.SaveAs(folder + fileName);
  // Unzip the file
  UnzipFile(filePath, folder);
  }
//After the folder has been transfered to the folder you can use the following code to unzip it.
  private void UnzipFile(string zipFilePath, string folder)
  {
  ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath));
  ZipEntry theEntry;
  while ((theEntry = s.GetNextEntry()) != null)
  {
  string directoryName = Path.GetDirectoryName(theEntry.Name);
  string fileName = Path.GetFileName(theEntry.Name);
  string serverFolder = Server.MapPath("~/Files/");
  // create directory
  Directory.CreateDirectory(serverFolder + directoryName);
  if (fileName != String.Empty)
  {
  FileStream streamWriter = File.Create((serverFolder + theEntry.Name));
  int size = 2048;
  byte[] data = new byte[2048];
  while (true)
  {
  size = s.Read(data, 0, data.Length);
  if (size > 0)
  {
  streamWriter.Write(data, 0, size);
  }
  else
  {
  break;
  }
  }
  streamWriter.Close();
  }
  }
  s.Close();
  }
download the sharezip lib from :
<http://www.sharpziplib.com/>
 
 
smr replied to Reshma Gurav on 27-Dec-11 07:32 AM
hi

try this

using System;
// This namespace contains the main class - ZipForge
// Don't forget to add a reference to the ZipForge
// assembly to your project references
using ComponentAce.Compression.ZipForge;
// This namespace contains ArchiverException class required for error handling
using ComponentAce.Compression.Archiver;
 
namespace UnzipFile
{
  class Program
  {
    static void Main(string[] args)
    {
      ZipForge archiver = new ZipForge();
      try
      {
        // The name of the ZIP file to unzip
        archiver.FileName = @"C:\test.zip";         
        // Open an existing archive
        archiver.OpenArchive(System.IO.FileMode.Open);
        // Default path for all operations         
        archiver.BaseDir = @"C:\Temp";
        // Extract all files from the archive to C:\Temp folder
        archiver.ExtractFiles("*.*");
        // Close archive
        archiver.CloseArchive();
      }
      // Catch all exceptions of the ArchiverException type
      catch (ArchiverException ae)
      {
        Console.WriteLine("Message: {0}\t Error code: {1}", ae.Message, ae.ErrorCode);
        // Wait for keypress
        Console.ReadLine();
      }
    }
  }
}

follow
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream%28VS.80%29.aspx#Y456
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/7120dac4-8fc5-4cde-ba69-5302251a0631
Devil Scorpio replied to Reshma Gurav on 27-Dec-11 08:13 AM
HI,

If you are manipulating ZIP files, you may want to look into a 3rd-party library to help you.

For example, DotNetZip, which has been recently updated. The current version is now v1.8. Here's an example to create a zip:

using (ZipFile zip = new ZipFile())
{
  zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
  zip.AddFile("c:\\Desktop\\2005_Annual_Report.pdf");
  zip.AddFile("ReadMe.txt");
  zip.Save("Archive.zip");
}


Here's an example to update an existing zip; you don't need to extract the files to do it:

using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
{
  // 1. remove an entry, given the name
  zip.RemoveEntry("README.txt");

  // 2. Update an existing entry, with content from the filesystem
  zip.UpdateItem("Portfolio.doc");

  // 3. modify the filename of an existing entry 
  // (rename it and move it to a sub directory)
  ZipEntry e = zip["Table1.jpg"];
  e.FileName = "images/Figure1.jpg";

  // 4. insert or modify the comment on the zip archive
  zip.Comment = "This zip archive was updated " + System.DateTime.ToString("G"); 

  // 5. finally, save the modified archive
  zip.Save();
}

here's an example that extracts entries:

using (ZipFile zip = ZipFile.Read("ExistingZipFile.zip"))
{
  foreach (ZipEntry e in zip)
  {
    e.Extract(TargetDirectory, true);  // true => overwrite existing files
  }
}

DotNetZip supports multi-byte chars in filenames, Zip encryption, AES encryption, streams, Unicode, self-extracting archives. Also does ZIP64, for file lengths greater than 0xFFFFFFFF, or for archives with more than 65535 entries.

free. open source
get it at http://www.codeplex.com/DotNetZip/Release/ProjectReleases.aspx?ReleaseId=18985 
Riley K replied to Reshma Gurav on 27-Dec-11 08:11 PM

The DotNetZip library, available at http://www.codeplex.com/DotNetZip , creates, reads, and extracts zipfiles. 

Create

using (ZipFile zip = new ZipFile("Archive.zip")) 
  
  zip.AddFile("ReadMe.txt"); 
  zip.AddFile("7440-N49th.png"); 
  zip.AddFile("2005_Annual_Report.pdf");     
  zip.Save(); 
  }

Read

using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 
  
  foreach (ZipEntry e in zip) 
  
    if (header) 
    
    System.Console.WriteLine("Zipfile: {0}", zip.Name); 
    if ((zip.Comment != null) && (zip.Comment != ""))  
      System.Console.WriteLine("Comment: {0}", zip.Comment); 
    System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}", 
                 "Filename", "Modified", "Size", "Ratio", "Packed", "pw?"); 
    System.Console.WriteLine(new System.String('-', 72)); 
    header = false; 
    
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}", 
                 e.FileName, 
                 e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), 
                 e.UncompressedSize, 
                 e.CompressionRatio, 
                 e.CompressedSize, 
                 (e.UsesEncryption) ? "Y" : "N"); 
    
  
  }

Extract

using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 
  
  foreach (ZipEntry e in zip) 
  
    e.Extract(TargetDirectory, true);  // overwrite == true 
  
  }


Regards
Jitendra Faye replied to Reshma Gurav on 28-Dec-11 12:10 AM
This use code-

A short alternative is ZipStorer (http://zipstorer.codeplex.com/). You don't need to use an external library (.DLL) as it is implemented in one .cs source file.
http://zipstorer.codeplex.com/

Extraction example:

// Open an existing zip file for reading
using (ZipStorer zip = ZipStorer.Open(@"c:\data\sample.zip", FileAccesss.Read))
{
  // Read the central directory collection
  List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

  // Look for the desired file
  foreach (ZipStorer.ZipFileEntry entry in dir)
  {
    if (Path.GetFileName(entry.FilenameInZip) == "sample.jpg")
    {
      // File found, extract it
      zip.ExtractStoredFile(entry, @"c:\data\sample.jpg");
      break;
    }
  }
}

Try this and let me know.
Reshma Gurav replied to Jitendra Faye on 28-Dec-11 04:39 AM
Thanks For the Reply..
Issue is solved.
Jitendra Faye replied to Reshma Gurav on 28-Dec-11 05:54 AM
You always welcome.