0 out of 2 rated this helpful - Rate this topic

ZipPackage Class

Implements a derived subclass of the abstract Package base class—the ZipPackage class uses a ZIP archive as the container store. This class cannot be inherited.

System.Object
  System.IO.Packaging.Package
    System.IO.Packaging.ZipPackage

Namespace:  System.IO.Packaging
Assembly:  WindowsBase (in WindowsBase.dll)
public sealed class ZipPackage : Package

The ZipPackage type exposes the following members.

  Name Description
Public property FileOpenAccess Gets the file access setting for the package. (Inherited from Package.)
Public property PackageProperties Gets the core properties of the package. (Inherited from Package.)
Top
  Name Description
Public method Close Saves and closes the package plus all underlying part streams. (Inherited from Package.)
Public method CreatePart(Uri, String) Creates a new uncompressed part with a given URI and content type. (Inherited from Package.)
Public method CreatePart(Uri, String, CompressionOption) Creates a new part with a given URI, content type, and compression option. (Inherited from Package.)
Protected method CreatePartCore When overridden in a derived class, creates a new part in the package. (Inherited from Package.)
Public method CreateRelationship(Uri, TargetMode, String) Creates a package-level relationship to a part with a given URI, target mode, and relationship type. (Inherited from Package.)
Public method CreateRelationship(Uri, TargetMode, String, String) Creates a package-level relationship to a part with a given URI, target mode, relationship type, and identifier (ID). (Inherited from Package.)
Public method DeletePart Deletes a part with a given URI from the package. (Inherited from Package.)
Protected method DeletePartCore When overridden in a derived class, deletes a part with a given URI. (Inherited from Package.)
Public method DeleteRelationship Deletes a package-level relationship. (Inherited from Package.)
Protected method Dispose Flushes and saves the content of all parts and relationships, closes the package, and releases all resources. (Inherited from Package.)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Flush Saves the contents of all parts and relationships that are contained in the package. (Inherited from Package.)
Protected method FlushCore When overridden in a derived class, saves the content of all parts and relationships to the derived class store. (Inherited from Package.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetPart Returns the part with a given URI. (Inherited from Package.)
Protected method GetPartCore When overridden in a derived class, returns the part addressed by a given URI. (Inherited from Package.)
Public method GetParts Returns a collection of all the parts in the package. (Inherited from Package.)
Protected method GetPartsCore When overridden in a derived class, returns an array of all the parts in the package. (Inherited from Package.)
Public method GetRelationship Returns the package-level relationship with a given identifier. (Inherited from Package.)
Public method GetRelationships Returns a collection of all the package-level relationships. (Inherited from Package.)
Public method GetRelationshipsByType Returns a collection of all the package-level relationships that match a given RelationshipType. (Inherited from Package.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method PartExists Indicates whether a part with a given URI is in the package. (Inherited from Package.)
Public method RelationshipExists Indicates whether a package-level relationship with a given ID is contained in the package. (Inherited from Package.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Explicit interface implemetation Private method IDisposable.Dispose This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended for application use. Use the type-safe Dispose method instead. (Inherited from Package.)
Top

The Package.Open method uses ZipPackage containers by default.

This example shows how to create a basic ZipPackage.

The example creates a package that contains a single document part which is defined as the package's root element by a package-level PackageRelationship.

The package also contains an image part and a second PackageRelationship which defines an association between the source document part and the target image part. (The image is a resource that is used with the document).


//  -------------------------- CreatePackage --------------------------
/// <summary>
///   Creates a package zip file containing specified
///   content and resource files.</summary>
private static void CreatePackage()
{
    // Convert system path and file names to Part URIs. In this example
    // Uri partUriDocument /* /Content/Document.xml */ =
    //     PackUriHelper.CreatePartUri(
    //         new Uri("Content\Document.xml", UriKind.Relative));
    // Uri partUriResource /* /Resources/Image1.jpg */ =
    //     PackUriHelper.CreatePartUri(
    //         new Uri("Resources\Image1.jpg", UriKind.Relative));
    Uri partUriDocument = PackUriHelper.CreatePartUri(
                              new Uri(documentPath, UriKind.Relative));
    Uri partUriResource = PackUriHelper.CreatePartUri(
                              new Uri(resourcePath, UriKind.Relative));

    // Create the Package
    // (If the package file already exists, FileMode.Create will
    //  automatically delete it first before creating a new one.
    //  The 'using' statement insures that 'package' is
    //  closed and disposed when it goes out of scope.)
    using (Package package =
        Package.Open(packagePath, FileMode.Create))
    {
        // Add the Document part to the Package
        PackagePart packagePartDocument =
            package.CreatePart(partUriDocument,
                           System.Net.Mime.MediaTypeNames.Text.Xml);

        // Copy the data to the Document Part
        using (FileStream fileStream = new FileStream(
               documentPath, FileMode.Open, FileAccess.Read))
        {
            CopyStream(fileStream, packagePartDocument.GetStream());
        }// end:using(fileStream) - Close and dispose fileStream.

        // Add a Package Relationship to the Document Part
        package.CreateRelationship(packagePartDocument.Uri,
                                   TargetMode.Internal,
                                   PackageRelationshipType);

        // Add a Resource Part to the Package
        PackagePart packagePartResource =
            package.CreatePart(partUriResource,
                           System.Net.Mime.MediaTypeNames.Image.Jpeg);

        // Copy the data to the Resource Part
        using (FileStream fileStream = new FileStream(
               resourcePath, FileMode.Open, FileAccess.Read))
        {
            CopyStream(fileStream, packagePartResource.GetStream());
        }// end:using(fileStream) - Close and dispose fileStream.

        // Add Relationship from the Document part to the Resource part
        packagePartDocument.CreateRelationship(
                                new Uri(@"../resources/image1.jpg",
                                UriKind.Relative),
                                TargetMode.Internal,
                                ResourceRelationshipType);

    }// end:using (Package package) - Close and dispose package.

}// end:CreatePackage()


//  --------------------------- CopyStream ---------------------------
/// <summary>
///   Copies data from a source stream to a target stream.</summary>
/// <param name="source">
///   The source stream to copy from.</param>
/// <param name="target">
///   The destination stream to copy to.</param>
private static void CopyStream(Stream source, Stream target)
{
    const int bufSize = 0x1000;
    byte[] buf = new byte[bufSize];
    int bytesRead = 0;
    while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
        target.Write(buf, 0, bytesRead);
}// end:CopyStream()


For the complete sample, see Writing a Package Sample.

.NET Framework

Supported in: 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
A VC++ Example
#using      <mscorlib.dll>
#using      <System.dll>
#using      <WindowsBase.dll>
using       namespace System;
using       namespace System::IO;
using       namespace System::IO::Packaging;
//----------------------------------------------------------------------------
// ZipFiles
//
// Creates the specified .zip file from the collection of files indicated by
// the specified array of files
//
// Note:    The resulting .zip file will contain a file called
//          [Content_Types].xml when it is unZIPped, and contains content
//          information about the types of files included in the .zip file.
//----------------------------------------------------------------------------
void ZipFiles(
    array <String ^> ^filesToZip,
    String ^zipFileName)
{
    if (filesToZip && filesToZip->Length && zipFileName && zipFileName->Length)
    {
        Package ^zipPackage = Package::Open(zipFileName, FileMode::Create);
        for each (String ^pathString in filesToZip)
        {
            if (pathString && File::Exists(pathString))
            {
                String ^zipURI =
                    String::Concat("/", Path::GetFileName(pathString)->Replace(" ", "_"));
                Uri ^partURI = gcnew Uri(zipURI, UriKind::Relative);
                PackagePart ^packagePart =
                    zipPackage->CreatePart(
                        partURI,
                        MediaTypeNames::Application::Zip,
                        CompressionOption::Normal);
                array <Byte> ^fileBytes = File::ReadAllBytes(pathString);
                packagePart->GetStream()->Write(fileBytes, 0, fileBytes->Length);
                delete [] fileBytes;
                delete partURI;
            }
        }
        zipPackage->Close();
        delete zipPackage;
    }
}
Erratta
Uri partUriDocument = PackUriHelper.CreatePartUri($0 new Uri(documentPath, UriKind.Relative)); Is wrong. Try $0 $0Uri partUriDocument = PackUriHelper.CreatePartUri( new Uri(Path.File(documentPath), UriKind.Relative)); Otherwise what you will get is a hidden folder inside the Zip folder with the name of the document path.$0 $0