Create Zip File

SharePoint Short #17

Not so much a SharePoint post, but can be used in a SharePoint project, so counts for me 🙂

Using the WindowsBase assembly provides access to the System.IO.Packaging namespace and the PackagePart class.

Using this class to create an in memory zip file containing one or more files is pretty straight forward:

public byte[] GetZipData()
{
    byte[] data;
    using (MemoryStream stream = new MemoryStream())
    {
        using (Package package = ZipPackage.Open(stream, FileMode.Create, FileAccess.ReadWrite))
        {
            // Wrap the rest of the using block in a for loop to iterate over files you want to
            // include in the package, this example only adds a single file.
 
            // Create the file to include in the zip
            Uri uri = PackUriHelper.CreatePartUri(new Uri("FileToIncludeInZip.txt", UriKind.Relative));
            PackagePart packagePart = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.Normal);
 
            using (Stream packagePartStream = packagePart.GetStream())
            {
                // Get content for file as byte array.
                byte[] packagePartData = Encoding.UTF8.GetBytes("content to write to FileToIncludeInZip.txt file");
                // Commit to package
                packagePartStream.Write(packagePartData, 0, packagePartData.Length);
            }
        }
 
        // Write stream content to data byte array
        data = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(data, 0, Convert.ToInt32(stream.Length));
    }
 
    return data;
}
 
// Code in you aspx page, WebPart, control, etc. :
 
byte[] data = GetZipData();
 
Page.Response.Buffer = true;
Page.Response.ClearHeaders();
Page.Response.ClearContent();
Page.Response.AddHeader("Content-Length", data.Length.ToString());
Page.Response.ContentType = "application/zip";
Page.Response.AppendHeader("Content-Disposition", "attachment;filename=DownloadableZipFile.zip");
Page.Response.BinaryWrite(data);
Page.Response.Flush();
Page.Response.Close();
This entry was posted in SharePoint Shorts and tagged . Bookmark the permalink.
0 0 votes
Article Rating
Subscribe
Notify of
guest

Solve the maths problem shown below before posting: *

0 Comments
Inline Feedbacks
View all comments