Building on my last post (http://toddvance.com/?p=231), we now know how to get data from a datatable and save it to a memoryStream.
To take this one step further, lets say we wanted to create a Zip file out of that data BUT didnt want to save it to our server for download. Let’s says we wanted to keep save it to memory and then out to the user of the site.
To do this, we first need a handy library available at codeplexhere : http://www.codeplex.com/DotNetZip – it’s called DotNetZip and provides some handy features for saving into zip format.
Stick that dll in your bin and reference it ( Imports Ionic.Utils.Zip ).
Now – from the last post, we have written the datatable to a memstream and then using a stringReader created a string out of that memoryStream.
Dim sr As New StreamReader(ms) ms.Seek(0, SeekOrigin.Begin) Dim mystring As String = sr.ReadToEnd sr.Close()
So now we have a string – from here we create a NEW memoryStream (we will need that to eventually write the file out from the browser) then using our new library, create a ZIP FILE that uses the memoryStream.
Dim memStr As MemoryStream = New MemoryStream Dim Zip As ZipFile = New ZipFile(memStr) Zip.AddFileFromString("myDataTable.txt", "", myString) Zip.Save() 'Set memoryStream to beginning position memStr.Position = 0 'Convert the Memory Stream into a Byte Array that we can stream to the browser 'send the memstr to the byte array by the .toArray Dim byteArray() As Byte byteArray = memStr.ToArray With HttpContext.Current.Response .ClearContent() .ClearHeaders() .AddHeader("Content-Disposition", "attachment;filename=ResearchExport.zip") .ContentType = "application/x-zip-compressed" .BinaryWrite(byteArray) .Flush() .Close() End With
This could be extended to allow people to save data they are viewing in your datagrid to a zip-text on their own computer….very nice.
