¿Necesitas empaquetar dinámicamente algunos archivos en un .zip para crear un paquete SCORM, cualquiera sabe cómo se puede hacer esto usando el código? ¿Es posible construir la estructura de carpetas dinámicamente dentro de .zip también?¿Cómo crear y llenar un archivo ZIP utilizando ASP.NET?
Respuesta
Ya no es necesario que use una biblioteca externa. System.IO.Packaging tiene clases que se pueden usar para colocar contenido en un archivo zip. No es simple, sin embargo. Here's a blog post with an example (está al final; excavar para obtenerlo).
El enlace no es estable, así que aquí está el ejemplo que Jon proporcionó en la publicación.
using System;
using System.IO;
using System.IO.Packaging;
namespace ZipSample
{
class Program
{
static void Main(string[] args)
{
AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe");
AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe");
}
private const long BUFFER_SIZE = 4096;
private static void AddFileToZip(string zipFilename, string fileToAdd)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = ".\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "",CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
{
long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long bytesWritten = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
{
outputStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
}
}
}
}
He usado un componente gratuito de chilkat para esto: http://www.chilkatsoft.com/zip-dotnet.asp. Hace casi todo lo que he necesitado; sin embargo, no estoy seguro sobre cómo construir dinámicamente la estructura de archivos.
Utilizamos también este componente en nuestra empresa. Basado en errores en el componente, algunos de nuestros servicios extremadamente estresados causaron una EngineException. Después de un Boleto de soporte de Microsoft, decidimos cambiar a SharpZLib. Esto fue hace 2 años. No sé qué tan bueno es el componente hoy en día? –
Nunca hemos tenido ningún problema, sin embargo, se usa en los servicios de exportación que, por lo general, se ejecutan como máximo cada hora, pero por lo general a diario.El cifrado también es útil – Macros
DotNetZip es bueno para esto. Working example
Puede escribir el zip directamente en Response.OutputStream. El código se ve así:
Response.Clear();
Response.BufferOutput = false; // for large files...
System.Web.HttpContext c= System.Web.HttpContext.Current;
String ReadmeText= "Hello!\n\nThis is a README..." + DateTime.Now.ToString("G");
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())
{
// filesToInclude is an IEnumerable<String>, like String[] or List<String>
zip.AddFiles(filesToInclude, "files");
// Add a file from a string
zip.AddEntry("Readme.txt", "", ReadmeText);
zip.Save(Response.OutputStream);
}
// Response.End(); // no! See http://stackoverflow.com/questions/1087777
Response.Close();
DotNetZip es gratis.
La creación de un archivo ZIP "sobre la marcha" se realizaría utilizando nuestro componente Rebex ZIP.
En el siguiente ejemplo se describe en su totalidad, incluyendo la creación de una subcarpeta:
// prepare MemoryStream to create ZIP archive within
using (MemoryStream ms = new MemoryStream())
{
// create new ZIP archive within prepared MemoryStream
using (ZipArchive zip = new ZipArchive(ms))
{
// add some files to ZIP archive
zip.Add(@"c:\temp\testfile.txt");
zip.Add(@"c:\temp\innerfile.txt", @"\subfolder");
// clear response stream and set the response header and content type
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=sample.zip");
// write content of the MemoryStream (created ZIP archive) to the response stream
ms.WriteTo(Response.OutputStream);
}
}
// close the current HTTP response and stop executing this page
HttpContext.Current.ApplicationInstance.CompleteRequest();
DotNetZip es muy fácil de usar ... Creating Zip files in ASP.Net
Si está utilizando .NET Framework 4.5 o más reciente que puede evitar bibliotecas de terceros y utilizar la clase nativa System.IO.Compression.ZipArchive
.
Aquí está un ejemplo de código rápida utilizando un MemoryStream y un par de matrices de bytes que representa dos archivos:
byte[] file1 = GetFile1ByteArray();
byte[] file2 = GetFile2ByteArray();
using (MemoryStream ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var zipArchiveEntry = archive.CreateEntry("file1.txt", CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file1, 0, file1.Length);
zipArchiveEntry = archive.CreateEntry("file2.txt", CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file2, 0, file2.Length);
}
return File(ms.ToArray(), "application/zip", "Archive.zip");
}
Se puede utilizar dentro de un controlador MVC devolver un ActionResult
: alternativamente, si es necesario físicamente crear el archivo zip, puede persistir el MemoryStream
en el disco o reemplazarlo por completo con un FileStream
.
Para obtener más información sobre este tema, también puede read this post.
- 1. ¿Cómo puedo extraer un solo archivo de un archivo ZIP utilizando Perl's Archive :: Zip?
- 2. crear carpeta para archivo zip y extraerla
- 3. Crear un archivo ZIP con Maven
- 4. Cómo crear un archivo Zip sin comprimir en Java
- 5. Crear un archivo ZIP cifrado en Python
- 6. Crear un archivo zip utilizando PHP clase ZipArchive sin escribir el archivo en el disco?
- 7. Cómo crear un archivo KML utilizando R
- 8. ¿Cómo puedo crear un archivo zip usando Objective C?
- 9. ¿Cómo puedo crear un archivo Zip en Perl?
- 10. MSBuild y ZIP crear archivos
- 11. ¿Cómo crear un archivo .zip desde mi directorio de documentos?
- 12. subdirectorios en el archivo Zip utilizando ZipOutputStream
- 13. ¿Cómo encriptar un archivo .zip?
- 14. ¿Crear un archivo zip de un generador en Python?
- 15. OutOfMemoryException al crear un archivo ZIP de gran tamaño utilizando System.IO.Packaging
- 16. ¿Cómo puedo generar y enviar un archivo .zip a un usuario en C# ASP.NET?
- 17. Crear archivo zip para descarga instantánea
- 18. Lea un archivo zip dentro del archivo zip
- 19. Crear archivo zip o tar.gz sin ejecutivo
- 20. Python: Cómo descargar un archivo zip
- 21. Crear un archivo zip del directorio "objetivo" maven
- 22. No es capaz de crear un archivo Zip en Gradle
- 23. Crear un archivo en Linux utilizando C
- 24. Crear un archivo ZIP desde una aplicación Cocoa
- 25. cómo llenar un modelo de vista en ASP.NET MVC3
- 26. ¿Cómo crear un archivo ZIP usando PHP y eliminarlo luego de que el usuario lo descargue?
- 27. Cómo crear un archivo ZIP para una lista de "archivos virtuales" y salida a httpservletresponse
- 28. Cómo actualizar un archivo en un archivo zip
- 29. Creando un archivo Zip desde la secuencia y descargándolo
- 30. Leer un archivo zip y escribirlo en otro archivo python
Posible duplicado de [Usando System.IO.Packaging para generar un archivo ZIP] (http://stackoverflow.com/questions/6386113/using-system-io-packaging-to-generate-a-zip-file) – Will