Creating Zip Files from Memory Stream C#

前端 未结 5 2155
执笔经年
执笔经年 2021-02-04 06:51

Basically the user should be able to click on one link and download multiple pdf files. But the Catch is I cannot create files on server or anywhere. Everything has to be in mem

5条回答
  •  庸人自扰
    2021-02-04 07:37

    Below is the code which is creating a zip file in MemoryStream using ZipOutputStream class which is exists inside ICSharpCode.SharpZipLib dll.

    FileStream fileStream = File.OpenRead(@"G:\1.pdf");
    MemoryStream MS = new MemoryStream();
    
    byte[] buffer = new byte[fileStream.Length];
    int byteRead = 0;
    
    ZipOutputStream zipOutputStream = new ZipOutputStream(MS);
    zipOutputStream.SetLevel(9); //Set the compression level(0-9)
    ZipEntry entry = new ZipEntry(@"1.pdf");//Create a file that is needs to be compressed
    zipOutputStream.PutNextEntry(entry);//put the entry in zip
    
    //Writes the data into file in memory stream for compression 
    while ((byteRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        zipOutputStream.Write(buffer, 0, byteRead);
    
    zipOutputStream.IsStreamOwner = false;
    fileStream.Close();
    zipOutputStream.Close();
    MS.Position = 0;
    

提交回复
热议问题