2009-08-31 54 views
7

Estoy tratando de agregar un archivo a un archivo existente usando el siguiente código. Cuando se ejecuta, no se muestran errores ni excepciones, pero tampoco se agregan archivos al archivo. ¿Alguna idea de por qué?C# sharpziplib agregar archivo al archivo existente

 using (FileStream fileStream = File.Open(archivePath, FileMode.Open, FileAccess.ReadWrite)) 
     using (ZipOutputStream zipToWrite = new ZipOutputStream(fileStream)) 
     { 
      zipToWrite.SetLevel(9); 

      using (FileStream newFileStream = File.OpenRead(sourceFiles[0])) 
      { 
       byte[] byteBuffer = new byte[newFileStream.Length - 1]; 

       newFileStream.Read(byteBuffer, 0, byteBuffer.Length); 

       ZipEntry entry = new ZipEntry(sourceFiles[0]); 
       zipToWrite.PutNextEntry(entry); 
       zipToWrite.Write(byteBuffer, 0, byteBuffer.Length); 
       zipToWrite.CloseEntry(); 

       zipToWrite.Close(); 
       zipToWrite.Finish(); 
      } 
     } 
+0

He actualizado mi respuesta. –

Respuesta

15

En DotNetZip, añadir archivos a una cuenta existente zip es realmente simple y confiable.

using (var zip = ZipFile.Read(nameOfExistingZip)) 
{ 
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; 
    zip.AddFile(additionalFileToAdd); 
    zip.Save(); 
} 

Si desea especificar una ruta de directorio para ese nuevo archivo, a continuación, utilizar una sobrecarga diferente para AddFile().

using (var zip = ZipFile.Read(nameOfExistingZip)) 
{ 
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; 
    zip.AddFile(additionalFileToAdd, "directory\\For\\The\\Added\\File"); 
    zip.Save(); 
} 

Si desea agregar un conjunto de archivos, use AddFiles().

using (var zip = ZipFile.Read(nameOfExistingZip)) 
{ 
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; 
    zip.AddFiles(listOfFilesToAdd, "directory\\For\\The\\Added\\Files"); 
    zip.Save(); 
} 

Usted no tiene que preocuparse de Close(), CloseEntry(), CommitUpdate(), Finalizar() o cualquiera de esas otras mugre.

+0

estoy empezando a odiar SharpZipLib, es demasiado baja nivelar y leer la documentación es confuso. –

1

creo que su llamada Finish debe ser antes de su Close llamada.

Actualización: Esto se parece a un known bug. Es posible que ya se haya corregido, deberá verificar su versión de SharpZipLib para ver si incorpora alguna solución. De lo contrario, puede solucionarlo copiando todos los archivos en un nuevo archivo, agregando el nuevo archivo y luego moviendo el nuevo archivo al antiguo nombre del archivo.

+0

hola, eso no hace ninguna diferencia .. aplausos. – Grant

2

De Codeproject alguien usó este código. La única diferencia es estrecha y terminar otherway alrededor y la parte de escritura:

using (ZipOutputStream s = new 
ZipOutputStream(File.Create(txtSaveTo.Text + "\\" + 
sZipFileName + ".zip"))) 
{ 
    s.SetLevel(9); // 0-9, 9 being the highest compression 

    byte[] buffer = new byte[4096]; 

    foreach (string file in filenames) 
    { 

     ZipEntry entry = new 
     ZipEntry(Path.GetFileName(file)); 

     entry.DateTime = DateTime.Now; 
     s.PutNextEntry(entry); 

     using (FileStream 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(); 
} 

Por cierto:

byte[] byteBuffer = new byte[newFileStream.Length - 1]; 

       newFileStream.Read(byteBuffer, 0, byteBuffer.Length); 

Esto es incorrecto, el tamaño es otra cosa newFileStream.length la Leer va mal. tiene una matriz y usted lo hace, por ejemplo 10-1 es de 9 bytes de longitud, de 0 a 8.

Pero su lectura de 0 a 9 ...

+0

Hola PoweRoy, he utilizado este código exactamente y todavía no hay errores, pero también hay un archivo :( – Grant

+0

también he probado este ZipFile ZipFile = new ZipFile (archivePath); zipFile.BeginUpdate(); entrada ZipEntry = nueva ZipEntry (nombre del archivo); zipFile.Add (nombre del archivo); zipFile.CommitUpdate();.. pero entonces los caminos están mal tengo que configurar las rutas relativas – Grant

1
/// <summary> 
    /// 添加压缩文件 p 为客户端传回来的文件/夹列表,用分号隔开,不包括主路径, zipfile压缩包的名称 
    /// </summary> 
    /// <param name="p"></param> 
    /// <param name="zipfile"></param> 
    public void AddZipFile(string p, string zipfile) 
    { 
     if (ServerDir.LastIndexOf(@"\") != ServerDir.Length - 1) 
     { 
      ServerDir += @"\"; 
     } 
     string[] tmp = p.Split(new char[] { ';' }); //分离文件列表 
     if (zipfile != "") //压缩包名称不为空 
     { 
      string zipfilepath=ServerDir + zipfile; 
      if (_ZipOutputStream == null) 
      { 
       _ZipOutputStream = new ZipOutputStream(File.Create(zipfilepath)); 
      } 
      for (int i = 0; i < tmp.Length; i++) 
      { 
       if (tmp[i] != "") //分离出来的文件名不为空 
       { 
        this.AddZipEntry(tmp[i], _ZipOutputStream, out _ZipOutputStream); //向压缩文件流加入内容 
       } 
      } 
     } 
    } 
    private static ZipOutputStream _ZipOutputStream; 
    public void Close() 
    { 
     _ZipOutputStream.Finish(); 
     _ZipOutputStream.Close(); 
    } 
-1

He encontrado una solución simple manteniéndola a ZipFile y ZipEntry única

 ZipFile zipExisting = ZipFile.Read(Server.MapPath("/_Layouts/includes/Template.zip")); 
     ICollection<ZipEntry> entries = _zipFileNew.Entries; 
     foreach (ZipEntry zipfile in entries) 
     { 
      zipExisting.AddEntry(zipfile.FileName, zipfile.InputStream); 
     } 

     zipExisting.Save(Response.OutputStream); 
     Response.End(); 
+0

Biblioteca incorrecta Fahar. – jpierson

0

hay una carpeta ZippedFolder en el directorio raíz del sitio, dentro de ella tenemos un archivo MyZipFiles.

Hay una carpeta con el nombre siteImages que consta de todos los archivos de imagen. El siguiente es el código para comprimir las imágenes

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip"); 
using (ZipFile zip = new ZipFile()) 
{ 
zip.AddFile(Server.MapPath("~/siteImages/img1.jpg"),string.Empty); 
zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty); 
zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty); 
zip.Save(zipPath); 
} 

si tenemos diferentes formatos de archivo y queremos que sus archivos que se guardan en las carpetas correspondientes, se puede especificar el código de la siguiente manera.

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip"); 
using (ZipFile zip = new ZipFile()) 
{ 
    zip.AddFile(Server.MapPath("~/siteimages/img1.jpg"), "images"); 
    zip.AddFile(Server.MapPath("~/siteimages/img2.jpg"), "images"); 
    zip.AddFile(Server.MapPath("~/documents/customer.pdf"), "files"); 
    zip.AddFile(Server.MapPath("~/documents/sample.doc"), "files"); 
    zip.Save(zipPath); 
} 

ahora el archivo contiene dos carpetas imágenes ----> img1.jpg, img2, .jpg y otra carpeta archivos -> customer.pdf, Sample.doc

0

La clase ZipOutputStream no actualiza los archivos ZIP existentes. Use la clase ZipFile en su lugar.

Cuestiones relacionadas