1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Zipping Files and folder using C#

Discussion in 'ASP.NET' started by naimish, Sep 9, 2009.

  1. naimish

    naimish New Member

    Joined:
    Jun 29, 2009
    Messages:
    1,046
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    On Earth

    Introduction



    Zipping Files and folder without using 3rd party tools

    Background



    Just add reference to the solution for vjslib available with C# .NET

    The code



    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Windows.Forms;
    using java.util;
    using java.util.zip;
    using java.io;
    namespace BHI.Rats
    {
        /// <summary>
        /// compression component
        /// </summary>
        public static class RatsCompressionManager
        {
            #region Compress and Uncompress
            /// <summary>
            /// Zips the folder name to create a zip file. 
            /// </summary>
            /// <remarks>The function is used for running as a worker thread</remarks>
            /// <param name="parameters">An array of 2 objects - folderName and zipFileName</param>
            public static void Zip(object parameters)
            {
                object[] parms = (object[])parameters;
                Zip((string)parms[0], (string)parms[1]);
            }
            /// <summary>
            /// Zips the folder name to create a zip file
            /// </summary>
            /// <param name="folderName"></param>
            /// <param name="zipFileName"></param>
            public static void Zip(string folderName, string zipFileName)
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fz.CreateZip(zipFileName, folderName, true, "");
                }
                catch (ICSharpCode.SharpZipLib.SharpZipBaseException)
                {
                    //Fail silently on cancel
                    if (Directory.Exists(folderName))
                    {
                        Directory.Delete(folderName, true);
                    }
                    if (System.IO.File.Exists(zipFileName))
                    {
                        System.IO.File.Delete(zipFileName);
                    }
                }
                catch
                {
                    //Close silently
                }
            }
            /// <summary>
            /// Compress list of files [sourceFiles] to [zipFileName]
            /// </summary>
            /// <param name="zipFileName"></param>
            /// <param name="sourceFiles"></param>
            public static void Zip(string zipFileName, FileInfo[] sourceFiles)
            {
                try
                {
                    // get the root folder. NOTE: it assums that the first file is at the root.
                    string rootFolder = Path.GetDirectoryName(sourceFiles[0].FullName);
                    // compress
                    ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fz.CreateZip(zipFileName, rootFolder, true, "");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// Extract [zipFileName] to [destinationPath]
            /// </summary>
            /// <param name="zipFileName"></param>
            /// <param name="destinationPath"></param>
            public static void Extract(string zipFileName, string destinationPath)
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fz.ExtractZip(zipFileName, destinationPath, "");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// Extract [zipFileName] to [destinationPath]
            /// </summary>
            /// <param name="zipFileName"></param>
            /// <param name="destinationPath"></param>
            /// <param name="fileNameToExtract">need to be the relative path in the zip file</param>
            public static void ExtractSingleFile(string zipFileName, string destinationPath, string fileNameToExtract)
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fz.ExtractZip(zipFileName, destinationPath, fileNameToExtract);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// Return a list of zip entries (compressed files meta data)
            /// </summary>
            /// <param name="zipFile"></param>
            /// <returns></returns>
            private static List<ZipEntry> getZippedFiles(ZipFile zipFile)
            {
                List<ZipEntry> zipEntries = new List<ZipEntry>();
                java.util.Enumeration zipEnum = zipFile.entries();
                while (zipEnum.hasMoreElements())
                {
                    ZipEntry zip = (ZipEntry)zipEnum.nextElement();
                    zipEntries.Add(zip);
                }
                return zipEntries;
            }
            /// <summary>
            /// Get the list of files in the zip file
            /// </summary>
            /// <param name="zipFileName"></param>
            /// <returns></returns>
            public static System.Collections.ArrayList GetZipEntries(string zipFileName)
            {
                System.Collections.ArrayList arrZipEntries = new System.Collections.ArrayList();
                ZipFile zipfile = new ZipFile(zipFileName);
                List<ZipEntry> zipFiles = getZippedFiles(zipfile);
                foreach (ZipEntry zipFile in zipFiles)
                {
                    arrZipEntries.Add(zipFile.getName());
                }
                zipfile.close();
                System.Collections.ArrayList arrZipEntriesInside = new System.Collections.ArrayList();
                foreach (string strZipFile in arrZipEntries)
                {
                    if (string.Compare(Path.GetExtension(strZipFile), ".zip", true) == 0)
                    {
                        ExtractSingleFile(zipFileName, Path.GetDirectoryName(zipFileName), Path.GetFileName(strZipFile));
                        ZipFile zipfileinside = new ZipFile(Path.GetDirectoryName(zipFileName) + Path.DirectorySeparatorChar + strZipFile);
                        List<ZipEntry> zipFilesInside = getZippedFiles(zipfileinside);
                        foreach (ZipEntry zipFile in zipFilesInside)
                        {
                            arrZipEntriesInside.Add(zipFile.getName());
                        }
                        zipfileinside.close();
                    }
                }
                foreach (string strFilesInsideZip in arrZipEntriesInside)
                {
                    arrZipEntries.Add(strFilesInsideZip);
                }
                return arrZipEntries;
            }
            /// <summary>
            /// Extract [zipFileName] to [destinationPath] recursively
            /// </summary>
            /// <param name="zipFileName"></param>
            public static void ExtractRecursively(string zipFileName)
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    fz.ExtractZip(zipFileName, Path.GetDirectoryName(zipFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(zipFileName), "");
                    DirectoryInfo diInputDir = new DirectoryInfo(Path.GetDirectoryName(zipFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(zipFileName));
                    FileInfo[] fiInfoArr = diInputDir.GetFiles("*.zip", SearchOption.AllDirectories);
                    foreach (FileInfo fiInfo in fiInfoArr)
                    {
                        if (string.Compare(Path.GetExtension(fiInfo.FullName), ".zip", true) == 0)
                        {
                            ExtractRecursively(fiInfo.FullName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
        }
    }
    


    Thank You :)

     
  2. milan bhatt

    milan bhatt New Member

    Joined:
    Sep 15, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    please tell where i need to run this c#.net code...
    and and how it zip the file & folder...
     
  3. naimish

    naimish New Member

    Joined:
    Jun 29, 2009
    Messages:
    1,046
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    On Earth
    You will need to add Reference of vjslib in your C#.NET code.

    Run it in .NET's C# Version.
     
  4. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Nice, but instead woh posting the whole class like this, you could have written about the the basic functions with small code snippets.
     
  5. naimish

    naimish New Member

    Joined:
    Jun 29, 2009
    Messages:
    1,046
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    On Earth
    I have been suggested to put much more descriptive code :D
     
  6. stevie teever

    stevie teever New Member

    Joined:
    Sep 30, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    you must check this code..
    This is not looks like the code of zip...
    i don't think that it is worth wile to consider as a zip code...
     
  7. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
  8. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    Thanks for the info, I appreciate it.
     
  9. technica

    technica New Member

    Joined:
    Dec 15, 2007
    Messages:
    107
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    have u written this code for yourself? Have u used it somewhere?
     
  10. amplemaddy

    amplemaddy New Member

    Joined:
    May 7, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    software engg
    Location:
    Chennai
    Code:
    //easy way to make zip files without any dlls
    //version indipendent
    public void MakeZip(string SourceFileName,string ZipFileName)// Zip functionality added by madhu
        {
            System.Diagnostics.Process scriptProc = new System.Diagnostics.Process();
            if (File.Exists(SourceFileName))
                {
                string command = "zip " + ZipFileName + " " + SourceFileName; // Building dos commands           
                System.Diagnostics.ProcessStartInfo procStartInfo =  new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                scriptProc.StartInfo = procStartInfo;
                scriptProc.Start();
                int id = scriptProc.Id; //get process id
                start:
                System.Diagnostics.Process[] processlist = System.Diagnostics.Process.GetProcessesByName("cmd");
                foreach (System.Diagnostics.Process theprocess in processlist) 
                {
                    if (theprocess.Id == id) //check proc id is found or not
                    {
                        goto start;
                    }                
                }
                scriptProc.Close();
            }
        }
     
    Last edited by a moderator: May 24, 2012

Share This Page