Trying to extract image from SQL Server in .NET, getting UnauthorizedAccessException

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?

  • C# and SQLServer normalizing large sets of Urls
  • How do UPDATE locks prevent a common form of deadlock?
  • Search criteria using Sql server
  • Filling the gaps in values of IDENTITY column
  • EF6 Does not generate foreign key association from database
  • SQL: how to get all the distinct characters in a column, across all rows
  • What can cause the SQL Server JDBC error 'The value is not set for the parameter number 0' for an output parameter access?
  • Retrieve corresponding foreign key with drop-down list (WCF) C#
  • Mass Renaming of Tables and Stored Procedures
  • MS SQL share identity seed amongst tables
  • Using DateTime in a SqlParameter for Stored Procedure, format error
  • SQL get values for only a few hours in given time period?
  • One Solution collect form web for “Trying to extract image from SQL Server in .NET, getting UnauthorizedAccessException”

    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 a MemoryStream at all, since you already have the bytes. You can do it like this:

        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(previewBytes, 0, previewBytes.Length)
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.