Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a .NET Stream of some content but Zip it up along the way

Tags:

c#

.net

stream

I have an XDocument which is large. I'm trying to stream this out somewhere:

public StreamResponse(Func<System.IO.Stream> source)

So to do this, I've done:

Stream stream = new MemoryStream();  // Create a stream
xmlDocument.Save(stream);      // Save XDocument into the stream
stream.Position = 0;

return new StreamResponse(() => stream);

and that works fine.

Now, is it possible to change this so that I stream out a ZIP of the memory stream.

like this => XDocument => MemoryStream => ZIP Stream => stream-end-point ?

like image 500
Pure.Krome Avatar asked Dec 07 '25 01:12

Pure.Krome


2 Answers

Stream stream = new MemoryStream();  // Create a stream
Stream compressed = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionLevel.Optimal);
xmlDocument.Save(compressed);      // Save XDocument into the stream
compressed.Position = 0;

return new StreamResponse(() => stream);

Documentation: GZipStream

like image 58
Petar Ivanov Avatar answered Dec 08 '25 15:12

Petar Ivanov


Yes, Use DotNetZip Pass your Memory Stream to the save method. Something like this:

     using (ZipFile zip = new ZipFile())
     {
         // add this map file into the "images" directory in the zip archive
         zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
         // add the report into a different directory in the archive
         zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
         zip.AddFile("ReadMe.txt");
         zip.Save(myStream);
     }
like image 45
Nathan Cooper Avatar answered Dec 08 '25 13:12

Nathan Cooper