Sunday, May 4, 2014

Downloading SharePoint List Item Attachments as Zip file

Downloading SharePoint List Item Attachments as Zip file

Using the Ionic DotNetZip library in the following location

The following is the code required to do this

 SPListItem item = List.GetItemById(ID);  
 SPAttachmentCollection attachmentCollection = item.Attachments;  
 Response.Clear();  
 string archiveName = String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));  
 Response.ContentType = "application/zip";  
 Response.AddHeader("content-disposition", "filename=" + archiveName);  
 using (ZipFile zip = new ZipFile())  
 {  
   foreach (string filename in attachmentCollection)  
   {  
     SPFile file = web.GetFile(attachmentCollection.UrlPrefix + filename);  
     Stream stream = file.OpenBinaryStream();  
     zip.AddEntry(file.Name, stream);  
   }  
   zip.Save(Response.OutputStream);  
   Response.Flush();  
 }  
 Response.Close();