Categorias

Criando seu próprio WINZIP com CSHARP

Esse código provê uma classe completa com exemplo para compactar e descompactar pastas e arquivos.

/*
 * CPZipStripper 2.0
 * Written by Decebal Mihailescu [https://www.codeproject.com/script/articles/list_articles.asp?userid=634640]
*/
using System;
using System.Collections.Generic;
using System.Text;
using java.util.zip;
using System.IO;


namespace CPZipStripper
{
    static class ZipUtility
    {
        static private string m_zipFolder;
        static private ZipOutputStream _zos = null;
        static private int m_trimIndex = 0;
        static private sbyte[] _buffer = new sbyte[2048];
        //public delegate bool IsFileStrippableDelegate(string fname);

        public static List GetZipFileNames(string zipFile)
        {
            ZipFile zf = null;
            List list = new List();
            try
            {
                zf = new ZipFile(zipFile);
                java.util.Enumeration enu = zf.entries();
                while (enu.hasMoreElements())
                {
                    ZipEntry zen = enu.nextElement() as ZipEntry;
                    if (zen.isDirectory())
                        continue;//ignore directories
                    list.Add(zen.getName());
                }

            }
            catch(Exception ex) 
            {
                throw new ApplicationException("Please drag/drop only valid zip filesnthat are not password protected.",ex);
            }
            finally
            {
                if (zf != null)
                    zf.close();               
            }
            return list;
        }


        public static void CreateZipFromFolder(string Folder, IsFileStrippableDelegate IsStrip)
        {
            try
            {
                string ParentDir = Directory.GetParent(Folder).FullName;
                m_trimIndex = ParentDir.Length;
                string root = Path.GetPathRoot(Folder);
                if (ParentDir != root)
                    m_trimIndex++;
                m_zipFolder = Folder;
                string strNewFile = m_zipFolder + ".zip";
                string fileName = Path.GetFileName(strNewFile);
                strNewFile = Path.GetDirectoryName(strNewFile) + @"" + fileName;
                //make room for the new zip
                System.IO.File.Delete(strNewFile + ".old");
                if (File.Exists(strNewFile))
                    System.IO.File.Move(strNewFile, strNewFile + ".old");
                _zos = new ZipOutputStream(new java.io.FileOutputStream(strNewFile));
                _CreateZipFromFolder(Folder, IsStrip);
            }//try ends
            catch (Exception ex)
            {
                throw new ApplicationException("unable to zip " + Folder + "folder", ex);
             }
            finally
            {
                if (_zos != null)
                    _zos.close();
                _zos = null;
                m_trimIndex = 0;
            }

        }
        private static void _CreateZipFromFolder(string Folder, IsFileStrippableDelegate IsStrip)
        {

            System.IO.DirectoryInfo dirInfo =
                new System.IO.DirectoryInfo(Folder);
            System.IO.FileInfo[] files = dirInfo.GetFiles("*");//all files
            foreach (FileInfo file in files)
            {
                if (IsStrip != null && IsStrip(file.FullName))
                    continue;//skip, don't zip it
                java.io.FileInputStream instream = new java.io.FileInputStream(file.FullName);
                int bytes = 0;
                string strEntry = file.FullName.Substring(m_trimIndex);
                _zos.putNextEntry(new ZipEntry(strEntry));
                while ((bytes = instream.read(_buffer, 0, _buffer.Length)) > 0)
                {
                    _zos.write(_buffer, 0, bytes);
                }
                _zos.closeEntry();
                instream.close();
            }

            System.IO.DirectoryInfo[] folders = null;
            folders = dirInfo.GetDirectories("*");
            if (folders != null)
            {
                foreach (System.IO.DirectoryInfo folder in folders)
                {
                    _CreateZipFromFolder(folder.FullName, IsStrip);
                }
            }

        }

        public static void StripZip(string zipFile, List trashFiles)
        {
            if (zipFile == null ||zipFile.Length == 0 || !File.Exists(zipFile))
            return;
            ZipOutputStream zos = null;
            ZipInputStream zis = null;
            //remove 'zip' extension
            bool bsuccess = true;
            string strNewFile = zipFile.Remove(zipFile.Length - 3, 3) + "tmp";
            try
            {
                zos = new ZipOutputStream(new java.io.FileOutputStream(strNewFile));
                zis = new ZipInputStream(new java.io.FileInputStream(zipFile));
                ZipEntry ze = null;
                while ((ze = zis.getNextEntry()) != null)
                {
                    if (ze.isDirectory())
                        continue;//ignore directories
                    string fname = ze.getName();
                    bool bstrip = trashFiles.Contains(fname);

                    if (!bstrip)
                    {
                        //copy the entry from zis to zos
                        int bytes = 0;
                        try
                        {
                            //deal with password protected files
                            zos.putNextEntry(new ZipEntry(fname));
                            while ((bytes = zis.read(_buffer, 0, _buffer.Length)) > 0)
                            {
                                zos.write(_buffer, 0, bytes);
                            }
                        }
                        catch (Exception)
                        {
                            bsuccess = false;
                            throw;
                        }
                        finally
                        {
                            zis.closeEntry();
                            zos.closeEntry();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                bsuccess = false;
                throw new ApplicationException("unable to zip/unzip: " + zipFile, ex);
            }
            finally
            {
                if (zis != null)
                    zis.close();
                if (zos != null)
                    zos.close();
                if (bsuccess)
                {
                    System.IO.File.Delete(zipFile + ".old");
                    System.IO.File.Move(zipFile, zipFile + ".old");
                    System.IO.File.Move(strNewFile, zipFile);
                }
                else
                {
                    System.IO.File.Delete(strNewFile);
                }
            }
        }

        public static void UnZip(string file, string Folder, IsFileStrippableDelegate IsStrip)
        {
            if (file == null || file.Length == 0 || !File.Exists(file))
                return;

            ZipInputStream zis = null;
            try
            {
                zis = new ZipInputStream(new java.io.FileInputStream(file));
                ZipEntry ze = null;
                while ((ze = zis.getNextEntry()) != null)
                {
                    if (ze.isDirectory())
                        continue;//ignore directories
                    string fname = ze.getName();
                    bool bstrip = IsStrip != null && IsStrip(fname);

                    if (!bstrip)
                    {
                        //unzip entry
                        int bytes = 0;
                        FileStream filestream = null;
                        BinaryWriter w = null;
                        try
                        {
                            string filePath = Folder + @"" + fname;
                            if(!Directory.Exists(Path.GetDirectoryName(filePath)))
                                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                            filestream = new FileStream(filePath, FileMode.Create);
                            w = new BinaryWriter(filestream);
                            
                            while ((bytes = zis.read(_buffer, 0, _buffer.Length)) > 0)
                            {
                                for (int i = 0; i < bytes; i++)
			                    {
                                    unchecked
                                    {
                                        w.Write((byte)_buffer[i]);
                                    }
			                    }
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            zis.closeEntry();
                            w.Close();
                            filestream.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("unable to unzip: " + file +"nIt might be password protected.", ex);
            }
            finally
            {
                if (zis != null)
                    zis.close();
            }

        }

    }
}

Arquivos para Download:

cpzipstripper_src.zip