Create and Send CSV Without Saving File to a Drive

You want to dynamically create a CSV file and make it available for download for your user.  But you don’t want to save the file to the drive.  You just want to create the file on the fly, send it to the user, and let it evaporate into thin air after it’s downloaded.  You can do that using a memorystream and streamwriter.

In this example, I take a datagrid, write its contents to a bytearray, and then send the array to the user as an http response.

Dim mstream As MemoryStream = New MemoryStream()
Dim writer As StreamWriter = New StreamWriter(mstream)
 
Dim Str As String
Dim i As Integer
Dim j As Integer
 
Dim headertext As String = "Col1,Col2,Col3"
writer.WriteLine(headertext)
For i = 0 To (Me.GridView1.Rows.Count - 1)
    For j = 0 To (Me.GridView1.Columns.Count - 1)
 
        'this IF statement stops it from adding a comma afterthe last field
        If j = (Me.GridView1.Columns.Count - 1) Then
            Str = (Me.GridView1.Rows(i).Cells(j).Text.ToString)
        Else
            Str = (Me.GridView1.Rows(i).Cells(j).Text.ToString & ",")
        End If
 
        writer.Write(Str)
    Next
    writer.WriteLine()
Next
 
writer.Flush()
writer.Close()
 
Dim byteArray As Byte() = mstream.ToArray()
 
mstream.Flush()
mstream.Close()
 
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=aFile.csv")
Response.AddHeader("Content-Length", byteArray.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteArray)
Response.Flush()
Response.Close()

Leave a Comment