Search This Blog

Monday, August 8, 2011

Zipping files in C# using SharpZipLib

  private void zipFiles()
        {
            try
            {
                string sTargetFolderPath = @"TargetFolderToZip";
                string sZipFileName = @"FileNametoZip";
                string[] filenames = Directory.GetFiles(sTargetFolderPath, "*.csv");
                // Zip up the files - From SharpZipLib Demo Code              
                using (ZipOutputStream s = new ZipOutputStream(File.Create(sTargetFolderPath + "\\" + sZipFileName + ".zip")))
                {
                    s.SetLevel(9); // 0-9, 9 being the highest 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(sTargetFolderPath + "file://tempzipfile//", true);               
            }
            catch (Exception ex)
            {
                //TODO: Exception Handling                               
            }
        }

No comments:

Post a Comment