Wednesday, 11 March 2015

Create a ZIP file using ICSharpCode.SharpZipLib in SharePoint 2010 webpart

Problem :    

We have to generate a zip file in SharePoint  webpart from a no of files present in a Physical path

Example : 
Files :   ABC.pdf, DEF.pdf, GHI.pdf

Zip file : xyz.zip 


Solution :

I have found the solution on web to use ICSharpCode.SharpZipLib(Free)  and convert the number of files into a single zip file.
Below is the code i have attached.

Parameter for below function:

arrFilesToZip - ArrayList with all the Full file Path name which you want to zip

FolderName - Full path of the folder where you want to save your zip file

sZipFileName- Zip file name


public string CreateZipfile(ArrayList arrFilesToZip, string folderName, string sZipFileName)
        {
            try
            {


                using (ZipOutputStream s = new ZipOutputStream(File.Create(folderName + "\\" + sZipFileName + ".zip")))
                {
                    s.UseZip64 = UseZip64.Off;
                    //s.IsStreamOwner = false;
                    ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                    foreach (string pathname in arrFilesToZip)
                    {
                        byte[] buffer = File.ReadAllBytes(pathname);

                        ZipEntry entry = new ZipEntry(Path.GetFileName(pathname));
                        entry.DateTime = DateTime.Now;
                        entry.Size = buffer.Length;
                        entry.CompressionMethod = CompressionMethod.Stored;

                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;

                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                    s.Finish();
                    s.Flush();
                    s.Close();
                }


                return folderName + "\\" + sZipFileName + ".zip";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Please let me know if you have any issue in understanding of code. 

Appreciate of any suggestion.:)


No comments:

Post a comment