ZipPackage Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Implementa una subclase derivada de la clase base abstracta Package : la ZipPackage clase usa un archivo ZIP como almacén de contenedores. Esta clase no puede heredarse.
public ref class ZipPackage sealed : System::IO::Packaging::Package
public sealed class ZipPackage : System.IO.Packaging.Package
type ZipPackage = class
inherit Package
Public NotInheritable Class ZipPackage
Inherits Package
- Herencia
Ejemplos
En este ejemplo se muestra cómo crear un elemento básico ZipPackage.
En el ejemplo se crea un paquete que contiene una sola parte de documento que se define como el elemento raíz del paquete mediante un nivel PackageRelationshipde paquete .
El paquete también contiene una parte de imagen y una segunda PackageRelationship que define una asociación entre la parte del documento de origen y la parte de imagen de destino. (La imagen es un recurso que se usa con el documento).
// -------------------------- 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
Comentarios
El paquete.Open el método usa ZipPackage contenedores de forma predeterminada.
Propiedades
| Nombre | Description |
|---|---|
| FileOpenAccess |
Obtiene la configuración de acceso a archivos para el paquete. (Heredado de Package) |
| PackageProperties |
Obtiene las propiedades principales del paquete. (Heredado de Package) |
Métodos
| Nombre | Description |
|---|---|
| Close() |
Guarda y cierra el paquete más todas las secuencias de elementos subyacentes. (Heredado de Package) |
| CreatePart(Uri, String, CompressionOption) |
Crea una nueva parte con un URI, un tipo de contenido y una opción de compresión determinados. (Heredado de Package) |
| CreatePart(Uri, String) |
Crea un nuevo elemento sin comprimir con un URI y un tipo de contenido especificados. (Heredado de Package) |
| CreatePartCore(Uri, String, CompressionOption) |
Cuando se invalida en una clase derivada, crea una nueva parte en el paquete. (Heredado de Package) |
| CreateRelationship(Uri, TargetMode, String, String) |
Crea una relación de nivel de paquete con un elemento con un URI determinado, el modo de destino, el tipo de relación y el identificador (ID). (Heredado de Package) |
| CreateRelationship(Uri, TargetMode, String) |
Crea una relación de nivel de paquete con un elemento con un URI determinado, el modo de destino y el tipo de relación. (Heredado de Package) |
| DeletePart(Uri) |
Elimina un elemento con un URI determinado del paquete. (Heredado de Package) |
| DeletePartCore(Uri) |
Cuando se invalida en una clase derivada, elimina un elemento con un URI determinado. (Heredado de Package) |
| DeleteRelationship(String) |
Elimina una relación de nivel de paquete. (Heredado de Package) |
| Dispose(Boolean) |
Vacía y guarda el contenido de todas las partes y relaciones, cierra el paquete y libera todos los recursos. (Heredado de Package) |
| Equals(Object) |
Determina si el objeto especificado es igual al objeto actual. (Heredado de Object) |
| Flush() |
Guarda el contenido de todas las partes y relaciones contenidas en el paquete. (Heredado de Package) |
| FlushCore() |
Cuando se invalida en una clase derivada, guarda el contenido de todas las partes y relaciones en el almacén de clases derivada. (Heredado de Package) |
| GetHashCode() |
Actúa como la función hash predeterminada. (Heredado de Object) |
| GetPart(Uri) |
Devuelve el elemento con un URI determinado. (Heredado de Package) |
| GetPartCore(Uri) |
Cuando se reemplaza en una clase derivada, devuelve la parte direccionada por un URI determinado. (Heredado de Package) |
| GetParts() |
Devuelve una colección de todas las partes del paquete. (Heredado de Package) |
| GetPartsCore() |
Cuando se invalida en una clase derivada, devuelve una matriz de todas las partes del paquete. (Heredado de Package) |
| GetRelationship(String) |
Devuelve la relación de nivel de paquete con un identificador determinado. (Heredado de Package) |
| GetRelationships() |
Devuelve una colección de todas las relaciones de nivel de paquete. (Heredado de Package) |
| GetRelationshipsByType(String) |
Devuelve una colección de todas las relaciones de nivel de paquete que coinciden con un determinado RelationshipType. (Heredado de Package) |
| GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
| MemberwiseClone() |
Crea una copia superficial del Objectactual. (Heredado de Object) |
| PartExists(Uri) |
Indica si un elemento con un URI determinado está en el paquete. (Heredado de Package) |
| RelationshipExists(String) |
Indica si una relación de nivel de paquete con un identificador determinado está contenida en el paquete. (Heredado de Package) |
| ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Implementaciones de interfaz explícitas
| Nombre | Description |
|---|---|
| IDisposable.Dispose() |
Este miembro admite la infraestructura de Windows Presentation Foundation (WPF) y no está pensada para el uso de aplicaciones. En su lugar, use el método de Dispose(Boolean) seguro para tipos. (Heredado de Package) |