Zip Multiple Files into one zip file

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;
    }
}


Recommended Free Ebook
Similar Articles