Package Class

Definition

表示一个可以存储多个数据对象的容器。Represents a container that can store multiple data objects.

public ref class Package abstract : IDisposable
public abstract class Package : IDisposable
type Package = class
    interface IDisposable
Public MustInherit Class Package
Implements IDisposable
Inheritance
Package
Derived
Implements

Examples

下面的示例演示了创建 Package的基本步骤。The following example shows the basic steps for creating a Package. 在此示例中,创建了一个包,其中包含一个作为文档一部分显示的图形图像。In this example, a package is created to contain a document together with a graphic image that is displayed as part of the document. (这类似于 HTML 文件具有引用外部图像文件的 <IMG > 标记的情况。) 包中还包括两个 PackageRelationship 元素。(This is similar to the case in which an HTML file has an <IMG> tag that references an external image file.) Two PackageRelationship elements are also included in the package. 第一种是 "包级别" 关系,它将文档部件定义为包的根元素。The first, a "package-level" relationship, defines the document part as the package's root element. 第二个 "part level" 关系定义文档部件(部分级别关系的 "源")和图像部分(部分级别关系的 "目标")之间的关联。A second, "part-level" relationship defines the association between the document part (the "source" of the part-level relationship) and its use of the image part (the "target" of the part-level relationship). 有关完整示例,请参阅编写包示例For the complete sample, see Writing a Package Sample.

//  -------------------------- 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()
'  -------------------------- CreatePackage --------------------------
''' <summary>
'''   Creates a package zip file containing specified
'''   content and resource files.</summary>
Private Shared Sub CreatePackage()
    ' Convert system path and file names to Part URIs. In this example
    ' Dim partUriDocument as Uri /* /Content/Document.xml */ =
    '     PackUriHelper.CreatePartUri(
    '         New Uri("Content\Document.xml", UriKind.Relative))
    ' Dim partUriResource as Uri /* /Resources/Image1.jpg */ =
    '     PackUriHelper.CreatePartUri(
    '         New Uri("Resources\Image1.jpg", UriKind.Relative))
    Dim partUriDocument As Uri = PackUriHelper.CreatePartUri(New Uri(documentPath, UriKind.Relative))
    Dim partUriResource As Uri = 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 As Package = Package.Open(packagePath, FileMode.Create)
        ' Add the Document part to the Package
        Dim packagePartDocument As PackagePart = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Text.Xml)

        ' Copy the data to the Document Part
        Using fileStream As New FileStream(documentPath, FileMode.Open, FileAccess.Read)
            CopyStream(fileStream, packagePartDocument.GetStream())
        End Using ' 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
        Dim packagePartResource As PackagePart = package.CreatePart(partUriResource, System.Net.Mime.MediaTypeNames.Image.Jpeg)

        ' Copy the data to the Resource Part
        Using fileStream As New FileStream(resourcePath, FileMode.Open, FileAccess.Read)
            CopyStream(fileStream, packagePartResource.GetStream())
        End Using ' 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 ' end:using (Package package) - Close and dispose package.

End Sub


'  --------------------------- 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 Shared Sub CopyStream(ByVal source As Stream, ByVal target As Stream)
    Const bufSize As Integer = &H1000
    Dim buf(bufSize - 1) As Byte
    Dim bytesRead As Integer = 0
    bytesRead = source.Read(buf, 0, bufSize)
    Do While bytesRead > 0
        target.Write(buf, 0, bytesRead)
        bytesRead = source.Read(buf, 0, bufSize)
    Loop
End Sub

Remarks

Package 是一种抽象类,可用于将对象组织成定义的物理格式的单个实体,以实现可移植性和高效访问。Package is an abstract class that can be used to organize objects into a single entity of a defined physical format for portability and efficient access.

ZIP 文件是 Package的主要物理格式。A ZIP file is the primary physical format for the Package. 其他 Package 实现可能使用其他物理格式,如 XML 文档、数据库或 Web 服务。Other Package implementations might use other physical formats such as an XML document, a database, or Web service.

与文件系统类似,Package 中包含的项在文件夹和文件的层次结构中进行引用。Like a file system, items contained in a Package are referenced in a hierarchical organization of folders and files.

尽管 Package 本身是抽象类,但 Open 方法使用 ZipPackage 派生类作为默认值。Although Package itself is an abstract class, the ZipPackage derived class is used as default by the Open method.

PackagePart ("part")是表示存储在 Package中的对象的抽象类。A PackagePart ("part") is the abstract class that represents an object that is stored in a Package.

PackageRelationship ("关系")定义源 PackagePackagePart 与目标对象之间的关联。A PackageRelationship ("relationship") defines an association between a source Package or PackagePart and a target object. PackageRelationship 可以是以下两种类型之一,其中每种类型可以是以下两种形式之一:A PackageRelationship can be one of two types, each of which can be one of two forms:

关系的源 Package 或源 PackagePart 被视为关系的 "所有者"。The relationship's source Package or source PackagePart is considered the "owner" of the relationship. 删除源对象时,还将删除源对象所拥有的所有关系。When the source object is deleted, all the relationships owned by the source object are also deleted. 创建或删除关系的过程不会以任何方式以物理方式更改源对象或目标对象。The process of creating or deleting a relationship does not physically change either the source or target objects in any way.

PackageDigitalSignature ("数字签名")是部件和关系的组合,表示包含在 Package中的数字签名。A PackageDigitalSignature ("digital signature") is a composition of parts and relationships representing a digital signature included with a Package. 数字签名标识发信方,并验证 Package 中包含的签名部分和关系是否尚未修改。The digital signature identifies the originator and validates that the signed parts and relationships contained in the Package have not been modified.

包还支持数字 Rights Management (DRM),这允许使用向授权用户授予的特定访问权限对 Package 中的内容元素进行加密。Packages also support Digital Rights Management (DRM) which allows content elements in a Package to be encrypted with specific access rights granted to authorized users.

根据 Package 的体系结构,XpsDocument 是设计用于基于 open XML 纸张规范(XPS)存储文档的包类型。Based on the Package architecture, an XpsDocument is a package type designed for storing documents based on the open XML Paper Specification (XPS).

默认情况下,.NET Framework 使用包来存储页面和文档的内容、资源和关系。The .NET Framework uses packages to store content, resources, and relationships for pages and documents using a standard ZIP file by default. 与任何 ZIP 文件一样,应用程序可以使用 System.IO.Packaging 类在单个有效访问权限容器中存储和(可选)保护任何类型或数量的数据文件。As with any ZIP file, your application can use the System.IO.Packaging classes to store and optionally protect any type or number of data files in a single efficient-to-access container.

有关详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=71255上可供下载的开放打包约定(OPC)规范。For more information, see the Open Packaging Conventions (OPC) specification available for download at https://go.microsoft.com/fwlink/?LinkID=71255.

Constructors

Package(FileAccess)

初始化使用给定的 PackageFileAccess 类的新实例。Initializes a new instance of the Package class that uses a given FileAccess.

Package(FileAccess, Boolean)

初始化使用给定 Package 和流选项的 FileAccess 类的新实例。Initializes a new instance of the Package class that uses a given FileAccess and streaming option.

Properties

FileOpenAccess

获取包的文件访问设置。Gets the file access setting for the package.

PackageProperties

获取包的核心属性。Gets the core properties of the package.

Methods

Close()

保存并关闭包和所有基础部件流。Saves and closes the package plus all underlying part streams.

CreatePart(Uri, String)

使用给定的 URI 和内容类型创建新的未压缩部件。Creates a new uncompressed part with a given URI and content type.

CreatePart(Uri, String, CompressionOption)

使用给定的 URI、内容类型和压缩选项创建新部件。Creates a new part with a given URI, content type, and compression option.

CreatePartCore(Uri, String, CompressionOption)

在派生类中重写时,会在包中创建一个新部件。When overridden in a derived class, creates a new part in the package.

CreateRelationship(Uri, TargetMode, String)

使用给定的 URI、目标模式和关系类型创建与部件的包级别关系。Creates a package-level relationship to a part with a given URI, target mode, and relationship type.

CreateRelationship(Uri, TargetMode, String, String)

使用给定的 URI、目标模式、关系类型和 标识符 (ID)identifier (ID) 创建与部件的包级别关系。Creates a package-level relationship to a part with a given URI, target mode, relationship type, and 标识符 (ID)identifier (ID).

DeletePart(Uri)

使用包中给定的 URI 删除部件。Deletes a part with a given URI from the package.

DeletePartCore(Uri)

在派生类中重写时,会使用给定的 URI 删除部件。When overridden in a derived class, deletes a part with a given URI.

DeleteRelationship(String)

删除包级别关系。Deletes a package-level relationship.

Dispose(Boolean)

刷新并保存所有部件和关系的内容,关闭包,并释放所有资源。Flushes and saves the content of all parts and relationships, closes the package, and releases all resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush()

保存包中包含的所有部件和关系的内容。Saves the contents of all parts and relationships that are contained in the package.

FlushCore()

在派生类中重写时,会将所有部件和关系的内容保存到派生类存储区中。When overridden in a derived class, saves the content of all parts and relationships to the derived class store.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetPart(Uri)

返回具有给定 URI 的部件。Returns the part with a given URI.

GetPartCore(Uri)

在派生类中重写时,会返回由给定 URI 寻址的部件。When overridden in a derived class, returns the part addressed by a given URI.

GetParts()

返回包中所有部件的集合。Returns a collection of all the parts in the package.

GetPartsCore()

在派生类中重写时,会返回包中所有部件的数组。When overridden in a derived class, returns an array of all the parts in the package.

GetRelationship(String)

返回具有给定标识符的包级别关系。Returns the package-level relationship with a given identifier.

GetRelationships()

返回所有包级别关系的集合。Returns a collection of all the package-level relationships.

GetRelationshipsByType(String)

返回与给定的 RelationshipType 匹配的所有包级别关系的集合。Returns a collection of all the package-level relationships that match a given RelationshipType.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Open(Stream)

在给定的 IO 流上打开包。Opens a package on a given IO stream.

Open(Stream, FileMode)

使用给定的 IO 流和文件模式打开包。Opens a package with a given IO stream and file mode.

Open(Stream, FileMode, FileAccess)

使用给定的 IO 流、文件模式和文件访问设置打开包。Opens a package with a given IO stream, file mode, and file access setting.

Open(String)

打开位于给定路径和文件名的包。Opens a package at a given path and file name.

Open(String, FileMode)

使用给定的文件模式打开位于给定路径的包。Opens a package at a given path using a given file mode.

Open(String, FileMode, FileAccess)

使用给定的文件模式和文件访问设置打开位于给定路径的包。Opens a package at a given path using a given file mode and file access setting.

Open(String, FileMode, FileAccess, FileShare)

使用给定的文件模式、文件访问和文件共享设置打开位于给定路径的包。Opens a package at a given path using a given file mode, file access, and file share setting.

PartExists(Uri)

指示具有给定 URI 的部件是否在包中。Indicates whether a part with a given URI is in the package.

RelationshipExists(String)

指示具有给定 ID 的包级别关系是否包含在包中。Indicates whether a package-level relationship with a given ID is contained in the package.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IDisposable.Dispose()

此成员支持 Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 基础结构,不是为应用程序使用而设计的。This member supports the Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) infrastructure and is not intended for application use. 改用类型安全的 Dispose(Boolean) 方法。Use the type-safe Dispose(Boolean) method instead.

Applies to

See also