PUBLICIDADE
Este código tem nota
10

Autor

francke

Francke Peixoto

membro deste setembro de 2007

Tags

Compartilhe e guarde

  • Rec6
  • StumbleUpon
  • ueba
  • linkk
  • dihitt
  • linkloko
  • linkto
  • Technorati
  • Simpy
  • del.icio.us
  • Faves: Fave It!

PUBLICIDADE

Enquete

Como você fará para aprender HTML5 / CSS3?

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 [http://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<string> GetZipFileNames(string zipFile)
        {
            ZipFile zf = null;
            List<string> list = new List<string>();
            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 files\nthat 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<string> 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();
            }

        }

    }
}

ArquivoTipoTamanhoHits 
cpzipstripper_src.zipArquivo ZIP25 Kb530Baixar o Arquivo
Sim   Não   Este código foi útil para você?
NotaComentário
10
passos25 comentou em 18/1/2009

legal

e usei e gostei muito
Regras:
Os comentários seguem as seguintes regras:
  • Todos os comentários são enviados por membros cadastrados no site.
  • A pontuação de comentários de conteúdo do próprio membro não serão computados.
  • Os comentários serão pré-aprovados, porém a equipe do site revisará o conteúdo de todos os comentários podendo ser invalidados (inclusive a pontuação).
  • Os comentários precisam ter, obrigatóriamente, coerência sobre o conteúdo que será comentado.
  • O membro que atingir 5 comentários invalidados não poderá mais comentar dentro do site. Com isso o membro não poderá mais ganhar pontos com comentários.
  • Há um limite de 10 comentários por dia para cada membro.
  • Qualquer comentário após ter sido publicado poderá ser retirado através da opção ( denunciar)

Comente

     (ainda não tem cadastro? clique aqui!)


Máximo de 30 caracteres

Máximo de 255 caracteres
 

R&W Consulting - Soluções Web Hospedagem UOL HOST PagSeguro - solução para pagamentos online
© 2006-2009 R&W Informática Ltda. - Todos os direitos reservados.