ZipOutputStream
solo comprimen archivos en una carpeta. Quiero comprimir subcarpetas también. ¿Cómo puedo conseguir esto?Las subcarpetas Zip que usan ZipOutputStream
Respuesta
Tienes que explorar recursivamente tu directorio para poder agregar todos los archivos en el zip.
ver este pequeño ayudante si lo desea:
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
namespace Zip
{
/// <summary>
/// Uses Sharpziplib so as to create a non flat zip archive
/// </summary>
public abstract class ZipManager
{
/// <summary>
/// will zip directory .\toto as .\toto.zip
/// </summary>
/// <param name="stDirToZip"></param>
/// <returns></returns>
public static string CreateZip(string stDirToZip)
{
try
{
DirectoryInfo di = new DirectoryInfo(stDirToZip);
string stZipPath = di.Parent.FullName + "\\" + di.Name + ".zip";
CreateZip(stZipPath, stDirToZip);
return stZipPath;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Main method
/// </summary>
/// <param name="stZipPath">path of the archive wanted</param>
/// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param>
public static void CreateZip(string stZipPath, string stDirToZip)
{
try
{
//Sanitize inputs
stDirToZip = Path.GetFullPath(stDirToZip);
stZipPath = Path.GetFullPath(stZipPath);
Console.WriteLine("Zip directory " + stDirToZip);
//Recursively parse the directory to zip
Stack<FileInfo> stackFiles = DirExplore(stDirToZip);
ZipOutputStream zipOutput = null;
if (File.Exists(stZipPath))
File.Delete(stZipPath);
Crc32 crc = new Crc32();
zipOutput = new ZipOutputStream(File.Create(stZipPath));
zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression
Console.WriteLine(stackFiles.Count + " files to zip.\n");
int index = 0;
foreach (FileInfo fi in stackFiles)
{
++index;
int percent = (int)((float)index/((float)stackFiles.Count/100));
if (percent % 1 == 0)
{
Console.CursorLeft = 0;
Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done.");
}
FileStream fs = File.OpenRead(fi.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//Create the right arborescence within the archive
string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1);
ZipEntry entry = new ZipEntry(stFileName);
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipOutput.PutNextEntry(entry);
zipOutput.Write(buffer, 0, buffer.Length);
}
zipOutput.Finish();
zipOutput.Close();
zipOutput = null;
}
catch (Exception)
{
throw;
}
}
static private Stack<FileInfo> DirExplore(string stSrcDirPath)
{
try
{
Stack<DirectoryInfo> stackDirs = new Stack<DirectoryInfo>();
Stack<FileInfo> stackPaths = new Stack<FileInfo>();
DirectoryInfo dd = new DirectoryInfo(Path.GetFullPath(stSrcDirPath));
stackDirs.Push(dd);
while (stackDirs.Count > 0)
{
DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();
try
{
//Process .\files
foreach (FileInfo fileInfo in currentDir.GetFiles())
{
stackPaths.Push(fileInfo);
}
//Process Subdirectories
foreach (DirectoryInfo diNext in currentDir.GetDirectories())
stackDirs.Push(diNext);
}
catch (Exception)
{//Might be a system directory
}
}
return stackPaths;
}
catch (Exception)
{
throw;
}
}
private static char[] _stSchon = new char[] { '-', '\\', '|', '/' };
}
}
Este artículo de C# MVP Peter Bromberg puede resolver su problema: Zip/Unzip folders and files with C#. Tiene un código completo y un proyecto de muestra.
alternativa (y más útil) solución Me tropecé con:
utilizando el proyecto SevenZipSharp
var compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
compressor.CompressionLevel = CompressionLevel.High;
compressor.CompressionMode = CompressionMode.Create;
compressor.PreserveDirectoryRoot = false;
compressor.FastCompression = true;
compressor.CompressDirectory(dir.FullName, zipFile.FullName);
public static void ZipDirectoryKeepRelativeSubfolder(string zipFilePath, string directoryToZip)
{
var filenames = Directory.GetFiles(directoryToZip, "*.*", SearchOption.AllDirectories);
using (var s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9);// 0 - store only to 9 - means best compression
var buffer = new byte[4096];
foreach (var file in filenames)
{
var relativePath = file.Substring(directoryToZip.Length).TrimStart('\\');
var entry = new ZipEntry(relativePath);
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (var fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
}
trabajado para mí, gracias – mrbm
el camino con terminar() y cerrar() funciona, no con el patrón Dispose. :( –
- 1. subdirectorios en el archivo Zip utilizando ZipOutputStream
- 2. Comprimir una carpeta que contiene subcarpetas
- 3. Cierre de ZipOutputStream
- 4. Git ignora las subcarpetas
- 5. Volviendo ZipOutputStream al navegador
- 6. Restaurar htacces para las subcarpetas
- 7. Se rechazarán las aplicaciones que usan telprompt
- 8. Proyectos que usan py.test
- 9. ¿Cómo es que las clases en las subcarpetas de mi carpeta App_Code no se encuentran correctamente?
- 10. enumerar las subcarpetas en una carpeta - Matlab (solo subcarpetas, no archivos)
- 11. ¿Cómo evalúa usted las clases que usan temporizadores internamente?
- 12. ¿Las fábricas abstractas usan "nuevo"?
- 13. Las variantes se usan recursivamente?
- 14. ¿Por qué deberíamos colocar las interfaces con las clases que las usan en lugar de las que las implementan?
- 15. ¿Qué componentes de RichFaces usan prototipo, que usan jquery?
- 16. Algunos ORM que usan PDO?
- 17. asp.net mvc - subcarpetas
- 18. ¿Cómo registrar HttpHandler para todas las subcarpetas en Asp.Net?
- 19. .htaccess 301 carpetas redireccionamiento, pero no las subcarpetas
- 20. Configuración de WordPress .htaccess para ver las subcarpetas
- 21. Eliminar carpeta CVS de todas las subcarpetas en windows
- 22. Cómo obtener archivos en las subcarpetas también desde el directorio
- 23. SVN ya no escribe .svn en todas las subcarpetas?
- 24. Django: dividir los comandos de administración en las subcarpetas
- 25. contraseña archivo zip protegido en Java
- 26. Subcarpetas en lib
- 27. SVN: Ignorar subcarpetas
- 28. Bash mkdir y subcarpetas
- 29. Copie el contenido de las subcarpetas con Ant
- 30. crear subcarpetas en NSDocumentDirectory
espero que no haya abandonado esta pregunta y estará de nuevo a marcar una respuesta o al menos indicar qué respuesta (s) fueron útiles. De tus más de 200 preguntas, tendrás aproximadamente 120 que necesitan una respuesta marcada (si se ha respondido satisfactoriamente), cada respuesta marcada te otorgará 2 puntos adicionales y ayuda a los futuros televidentes de tu pregunta a saber cuál fue la mejor respuesta. . 120 * 2rep = 240 repeticiones que podría ganar. – slugster