• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1297
  • Last Modified:

System.OutOfMemoryException when using SqlDataReader.GetBytes

I am losing my mind with this one. I am attempting to pull a HUGE file (41,656,832 bytes) from SQL Server and stream it to the client (browser) and keep running up against a mysterious "System.OutOfMemoryException" error.

Dim colIndex As Integer = 0                                         'objDR.GetOrdinal(m_sDocRepBinColumn)
Dim startIndex As Integer = 0, bufferSize As Integer = 4096         '1048576
Dim fileBuffer(bufferSize - 1) As Byte
Dim bytesInBuffer As Long

'Read into the buffer
'************* THIS VERY FIRST LINE CAUSES AN ERROR!!! ********************
bytesInBuffer = objDR.GetBytes(colIndex, startIndex, fileBuffer, 0, bufferSize)

'Write in the loop ONLY IF the bytes read exactly fill the buffer
Do While bytesInBuffer = bufferSize

    startIndex += bytesInBuffer
    bytesInBuffer = objDR.GetBytes(colIndex, startIndex, fileBuffer, 0, bufferSize)

'Write out the remaining bytes, if any
If bytesInBuffer > 0 Then
    Dim lastFewBytes(bytesInBuffer - 1) As Byte
    Array.Copy(fileBuffer, 0, lastFewBytes, 0, bytesInBuffer)

End If

Open in new window

I am using the System.Data.SqlClient.SqlDataReader object and returning the BLOB (IMAGE column from SQL Server 2000) by itself (no other columns) and still this call fails with this error.

This same code seems to work a few times AFTER an IIS RESET, but eventually fails and continues to fail until another reset.

Smaller files (20,628,882 bytes) seem to work just fine with this same code.

Notice, also, that I started with a 1MB buffer (1024x1024) but reduced it to 4k (1024x4) just to get that first call to GetBytes() to succeed. (It's this first call that fails each time.)

I have searched EE & Google with NO LUCK.
  • 2
1 Solution
PentegraAuthor Commented:
Changing it to SequentialAccess seems to have done the trick for me.


PentegraAuthor Commented:
Calling the ExecuteReader method with the CommandBehavior.SequentialAccess argument did the trick for me.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now