Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » C# Language » To Zip Multiple Files into one zip file

To Zip Multiple Files into one zip file

Describing how to zip more than one file into single zip file and how to skip zip file more zipping.

Page Views : 31102
Downloads : 15
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


As My previous article, I described, how to zip a file (any file). But sometimes, you need to zip more than one file into single zip file; e.g. Mail attachment that take so much time on attachment or sometimes space limit problem. It to be better to zip attachment files into one file.

 

I searched and got a DLL file which providing multiple file zipping. I use it and develop a function which takes two parameters; one folder which to zip and no of files of that folder (you may take it within function but I have already taken files that's why I use it as parameter)

 

How it works:

 

I create a temp folder where I will copy all files from actual folder. Remember it only zip those files which don't have .zip extension (if you need, you may skip that code area). Then get files from temp folder and set zip file name (I am giving current date and time). I create an object of ZipOutputStream (class contained by imported DLL file) which writes zip data (as zip file) on stream then close it.

 

public static void ZipMultiFiles(string dirwhereZip, FileInfo[] nfiles)

{

    try

    {

        if (nfiles.Length.Equals(0))

        {

            return;

        }

        string[] sTemp = dirwhereZip.Split('\\');

        string sZipFileName = sTemp[sTemp.Length - 1].ToString();

 

        // Check for the existence of the target folder and

        // create it if it does not exist

        if (!System.IO.Directory.Exists(dirwhereZip + "\\TempZipFile\\"))

        {

             System.IO.Directory.CreateDirectory(dirwhereZip + "\\TempZipFile\\");

        }

 

        // Set up a string to hold the path to the temp folder

      

        //FileInfo fi2 = new FileInfo(file.FullName);

        if (file.Exists)

        {

            // move it to the folder

            try

            {

                int existExension = Microsoft.VisualBasic.Strings.InStr(file.Name, ".zip", CompareMethod.Text);

                if (existExension != 0)

                continue;

                file.CopyTo(sTargetFolderPath + file.Name, true);

                file.Delete();

            }

            catch

            {

                // clean up if the operation failed

                System.IO.Directory.Delete(sTargetFolderPath);

                MessageBox.Show("Could not copy files to temp folder.", "File Error");

                return;

            }

        }

    }

    // zip up the files

    string[] filenames = Directory.GetFiles(sTargetFolderPath);

    DateTime current = DateTime.Now;

    string zipfName = "Request" + current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString();

     // Zip up the files - From SharpZipLib Demo Code

     using (ZipOutputStream s = new ZipOutputStream(File.Create(dirwhereZip + "\\" + zipfName + ".zip")))

     {

         s.SetLevel(9); // 0-9, 9 being the highest level of compression

 

         byte[] buffer = new byte[4096];

 

         foreach (string file in filenames)

         {

             ZipEntry entry = new ZipEntry(Path.GetFileName(file));

 

             entry.DateTime = DateTime.Now;

             s.PutNextEntry(entry);

 

             using (FileStream fs = File.OpenRead(file))

             {

                 int sourceBytes;

                 do

                 {

                     sourceBytes = fs.Read(buffer, 0, buffer.Length);

                     s.Write(buffer, 0, sourceBytes);

 

                 }

                 while (sourceBytes > 0);

             }

         }

         s.Finish();

         s.Close();

     }

 

      // clean up files by deleting the temp folder and its content

      System.IO.Directory.Delete(dirwhereZip + "\\TempZipFile\\", true);

   }

    catch (Exception ex)

   {

       throw ex;

   }

}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by anil panwar on Jan 12, 2011
Very Gud article ..... Thnx  a lot...

but i am not able to download  source code for this article ...
please give me source code....
Contents added by Muhammad Shakir on Mar 14, 2010
Download File: ICSharpCode.SharpZipLib.rar.zip
Its actually .rar file. Remove .zip text and then decompress it. you will get the file
 [Top] Rate this article
 
 About the author
 
Muhammad Shakir
I am Muhammad Ahsan Shakir. i completed my BS(CS) in 2006. Currently doing MSc in Mobile Computing from University of Bradford (U.K). My speciality is cryptograhy,ADO.net, Asp.net (VB & C#), VB 6.0, C/C++, osCommerace, and Joomla. i like to work in IT sector
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Imported dll by D On December 26, 2007
So where is the imported Dll? DO you have a link for it?
Reply | Email | Modify 
zip files by jay On September 18, 2008
after zipping files the session gets terminated..Pls help
Reply | Email | Modify 
zip in web by Arnab On October 1, 2009
hello,
i am very new in .net. i want to know how can i zip and save  a file when a user upload the file by file upload tools?pls help . it will be better for me if you ipload a demo project.or mailme at arnabpatra143@gmail.com.
Reply | Email | Modify 
Comments by asp On December 2, 2009
hi
what is file.exist
'file' which type of Variable it is.

Reply | Email | Modify 
Re: Comments by Muhammad On December 4, 2009
it is file which you want to zip it.
Reply | Email | Modify 
source file with ddl? by loopbe On December 14, 2009
Hey, I am interested this project also, because i am working on my project which include creating zip file from Multiple Files. Can you send me an source files? here is my email: loopbe@gmail.com thanks

Reply | Email | Modify 
A Good Article by Jianguo On May 5, 2011
Thanks a lot.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.