Byte array truncates my memorystream

G

Guest

Hi,
I'm trying to download a memorystream to a .csv file on the users desktop.
When I go to write out the memorystream through the byte array it seems to
truncate at 1024 and I don't know how to increase the size. Here is my code
if that helps.

Thanks.

Dim msw As MemoryStream = New MemoryStream
msw.SetLength(5000)

Dim sw As New StreamWriter(msw)

' First we will write the headers.
Try
Dim strBuffer As String = ""
Dim c As Integer
Dim dt As DataTable = CType(Session("GridData"), DataTable)
Dim iColCount As Integer = dt.Columns.Count

For c = 0 To iColCount - 1
strBuffer += dt.Columns(c).ToString

If (c < iColCount - 1) Then
strBuffer += ","
End If
Next

strBuffer += ControlChars.NewLine

' Now write all the rows.
Dim dr As DataRow
For Each dr In dt.Rows

For c = 0 To iColCount - 1
strBuffer += (dr(c).ToString)

If (c < iColCount - 1) Then
strBuffer += (",")
End If

Next
strBuffer += ControlChars.NewLine
Next
sw.Write(strBuffer)

Dim byteArray() As Byte = msw.ToArray()

msw.Flush()
msw.Close()
Response.Clear()

'Add Headers to enable dialog display
Response.AddHeader("Content-Disposition", "attachment;
filename=TownGrants.csv")
Response.AddHeader("Content-Length", byteArray.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteArray)

Catch ex As Exception

End Try
 
C

Christian Benien

You can try a sw.Flush() before you call msw.ToArray(), because the
StreamWriter has an internal buffer. Additionally, you should replace
the string concatenation with a StringBuilder for performance reasons
(if the data has more than 100 fields)
 
J

Jon Skeet [C# MVP]

Gambler said:
I'm trying to download a memorystream to a .csv file on the users desktop.
When I go to write out the memorystream through the byte array it seems to
truncate at 1024 and I don't know how to increase the size. Here is my code
if that helps.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

You should also consider writing to the StreamWriter every time you are
currently appending to strBuffer - there's no need for strBuffer, and
it's very inefficient to keep creating a new string each time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top