In .NET 4.5, the System.IO.Compression library has been added to work with data compression (archiving), including working with streams. Try, for example, like this:
//Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ Π½ΠΎΠ²ΡΠΉ ΠΏΠΎΡΠΎΠΊ Π² ΠΏΠ°ΠΌΡΡΠΈ FileStream fZip = new MemoryStream(); //Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ Π²ΡΡ
ΠΎΠ΄Π½ΠΎΠΉ ZIP-ΠΏΠΎΡΠΎΠΊ ZipOutputStream zipOStream = new ZipOutputStream(fZip); //Π‘ΠΊΠ°Π½ΠΈΡΡΠ΅ΠΌ Π΄ΠΈΡΠ΅ΠΊΡΠΎΡΠΈΡ sourceDirectory Π² ΠΏΠΎΠΈΡΠΊΠ°Ρ
ΡΠ°ΠΉΠ»ΠΎΠ² var allfiles = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.AllDirectories); //ΠΠ±ΡΠ°Π±Π°ΡΡΠ²Π°Π΅ΠΌ ΠΊΠ°ΠΆΠ΄ΡΠΉ Π½Π°ΠΉΠ΄Π΅Π½Π½ΡΠΉ ΡΠ°ΠΉΠ» foreach (FileInfo fi in allfiles) { //ΠΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ Π½ΠΎΠ²ΡΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Π°ΡΡ
ΠΈΠ²Π° ZipEntry entry = new ZipEntry((fi.Name)); zipOStream.PutNextEntry(entry); //ΠΡΠΊΡΡΠ²Π°Π΅ΠΌ ΡΠ°ΠΉΠ» ΠΊΠ°ΠΊ ΠΏΠΎΡΠΎΠΊ ΠΈ ΡΠΈΡΠ°Π΅ΠΌ Π΅Π³ΠΎ Π² ZIP-ΠΏΠΎΡΠΎΠΊ FileStream fs = File.OpenRead(fi.FullName); try { byte[] transferBuffer[1024]; do { bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length); zipOStream.Write(transferBuffer, 0, bytesRead); } while (bytesRead > 0); } finally { fs.Close(); } } //ΠΠ°ΠΊΡΡΠ²Π°Π΅ΠΌ Π½Π°Ρ ΠΏΠΎΠ»ΡΡΠΈΠ²ΡΠΈΠΉΡΡ ZIP-ΠΏΠΎΡΠΎΠΊ, ΡΠ΅ΠΏΠ΅ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΠΎΡΠ΄Π°Π²Π°ΡΡ Π΅Π³ΠΎ ΠΊΠ»ΠΈΠ΅Π½ΡΡ. zipOStream.Finish(); zipOStream.Close();
Another option:
var allfiles = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.AllDirectories); using (var memoryStream = new MemoryStream()) { //Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΠΎΡΠΎΠΊ Π΄Π»Ρ Π°ΡΡ
ΠΈΠ²Π° Π² ΠΏΠ°ΠΌΡΡΠΈ. using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { foreach (var f in allfiles) { var demoFile = archive.CreateEntry(f); } } memoryStream.Seek(0, SeekOrigin.Begin); //Π’Π΅ΠΏΠ΅ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΊΠΎΠΏΠΈΡΠΎΠ²Π°ΡΡ Π² ΡΠ°ΠΉΠ»ΠΎΠ²ΡΠΉ ΠΏΠΎΡΠΎΠΊ, Π½Π°ΠΏΡΠΈΠΌΠ΅Ρ (Π±ΡΠ΄Π΅Ρ zip-Π°ΡΡ
ΠΈΠ²) ΠΈΠ»ΠΈ ΠΎΡΠ΄Π°ΡΡ ΠΏΠΎΡΠΎΠΊ ΠΊΠ»ΠΈΠ΅Π½ΡΡ: //memoryStream.CopyTo(fileStream); } }
The variant with the archive from the byte array just for ASP .NET MVC is given in English SO . Let me copy the code here:
using (var compressedFileStream = new MemoryStream()) { //Create an archive and store the stream in memory. using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false)) { foreach (var caseAttachmentModel in caseAttachmentModels) { //Create a zip entry for each attachment var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name); //Get the stream of the attachment using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body)) { using (var zipEntryStream = zipEntry.Open()) { //Copy the attachment stream to the zip entry stream originalFileStream.CopyTo(zipEntryStream); } } } } return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" }; }
MemoryStreamfor compression. As far as I remember, the class for working with ZIP in .NET 4.5 quite allows itself this, and already give the user the resulting stream MemoryStream. - BlackWitcher 1:58 pmbyte[]) and return a variable with an array. - BlackWitcher