I am trying to extract a byte string in .NET from a SQL Server database and convert it to an image. My Code looks something like this
Dim strqry As String = "SELECT preview FROM dbo.AmazonS3FilePreview WHERE fileKey ='" + incomingKey + "'"
Dim myComm As SqlCommand = New SqlCommand(strqry, myConn)
Dim resultReader As SqlDataReader = myComm.ExecuteReader
Dim previewBytes As Byte() = Nothing
While resultReader.Read()
previewBytes = DirectCast(resultReader.Item("preview"), Byte())
End While
If Not previewBytes Is Nothing Then
Dim ms As MemoryStream = New MemoryStream(previewBytes)
Response.ContentType = "image/jpeg"
Response.OutputStream.Write(ms.GetBuffer, 0, ms.GetBuffer.Length)
Response.AddHeader("Content-Disposition", "attachment;filename=" + incomingKey)
End If
However on the line Response.OutputStream.Write(ms.GetBuffer, 0, ms.GetBuffer.Length) I get an error saying UnauthorizedAccessException: MemoryStream's internal buffer cannot be accessed. I can definitely read regular char columns in the database, why are there issues with reading bytes?
You don’t need to use
GetBuffer, and anyway you shouldn’t (it’s the internal buffer, which is larger than the actual data, so its length is meaningless). Actually, you don’t need aMemoryStreamat all, since you already have the bytes. You can do it like this: