| 1 | using System;
|
|---|
| 2 | using System.IO;
|
|---|
| 3 | using ICSharpCode.SharpZipLib.Zip;
|
|---|
| 4 |
|
|---|
| 5 | namespace Updater.Helpers
|
|---|
| 6 | {
|
|---|
| 7 | public class ZipHelper
|
|---|
| 8 | {
|
|---|
| 9 | /// <summary>Extracts the specified zip file with its directory hierarchy</summary>
|
|---|
| 10 | /// <param name="file">Zip file to be extracted</param>
|
|---|
| 11 | /// <param name="folder">New folder that the zip will be extracted into</param>
|
|---|
| 12 | /// <param name="delete">Delete or keep the original zip after extracting</param>
|
|---|
| 13 | public static void Extract(string file, string folder, bool delete)
|
|---|
| 14 | {
|
|---|
| 15 | if (!file.ToLower().EndsWith(".zip"))
|
|---|
| 16 | throw new ApplicationException("Check your file format");
|
|---|
| 17 |
|
|---|
| 18 | if (!File.Exists(file))
|
|---|
| 19 | throw new ApplicationException("Zip file does not exist");
|
|---|
| 20 |
|
|---|
| 21 | if (!Directory.Exists(folder))
|
|---|
| 22 | Directory.CreateDirectory(folder);
|
|---|
| 23 |
|
|---|
| 24 | using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(file)))
|
|---|
| 25 | {
|
|---|
| 26 | ZipEntry zipEntry;
|
|---|
| 27 |
|
|---|
| 28 | while ((zipEntry = zipInputStream.GetNextEntry()) != null)
|
|---|
| 29 | {
|
|---|
| 30 | string zipDirectory = Path.GetDirectoryName(zipEntry.Name);
|
|---|
| 31 | string zipFile = Path.GetFileName(zipEntry.Name);
|
|---|
| 32 | if (zipDirectory.Length > 0)
|
|---|
| 33 | Directory.CreateDirectory(folder + Path.DirectorySeparatorChar + zipDirectory);
|
|---|
| 34 |
|
|---|
| 35 | if (!string.IsNullOrEmpty(zipFile))
|
|---|
| 36 | {
|
|---|
| 37 | DecompressAndWriteFile(folder + Path.DirectorySeparatorChar + zipEntry.Name, zipInputStream);
|
|---|
| 38 | }
|
|---|
| 39 | }
|
|---|
| 40 | }
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | private static void DecompressAndWriteFile(string destination, ZipInputStream source)
|
|---|
| 44 | {
|
|---|
| 45 | FileStream wstream = null;
|
|---|
| 46 |
|
|---|
| 47 | try
|
|---|
| 48 | {
|
|---|
| 49 | // create a stream to write the file to
|
|---|
| 50 | wstream = File.Create(destination);
|
|---|
| 51 |
|
|---|
| 52 | const int block = 2048; // number of bytes to decompress for each read from the source
|
|---|
| 53 |
|
|---|
| 54 | byte[] data = new byte[block]; // location to decompress the file to
|
|---|
| 55 |
|
|---|
| 56 | // now decompress and write each block of data for the zip file entry
|
|---|
| 57 | while (true)
|
|---|
| 58 | {
|
|---|
| 59 | int size = source.Read(data, 0, data.Length);
|
|---|
| 60 |
|
|---|
| 61 | if (size > 0)
|
|---|
| 62 | wstream.Write(data, 0, size);
|
|---|
| 63 | else
|
|---|
| 64 | break; // no more data
|
|---|
| 65 | }
|
|---|
| 66 | }
|
|---|
| 67 | finally
|
|---|
| 68 | {
|
|---|
| 69 | if (wstream != null)
|
|---|
| 70 | wstream.Close();
|
|---|
| 71 | }
|
|---|
| 72 | }
|
|---|
| 73 | }
|
|---|
| 74 | } |
|---|