1

I have a table with varbinary column:

My table {
   Id int primary key,
   FileBody varbinary(max)     
}

Now I want to read it. It's simple I can use code like in this answer but it converts varbinary to byte[] and I want to avoid it.

Is it possible to put varbinary in MemoryStream without converting to a byte[]?

Community
  • 1
  • 1
Kliver Max
  • 5,107
  • 22
  • 95
  • 148
  • There is no conversion, think of it more like a buffer to move the data from the sql server into a memorystream. To save on memory you could use smaller buffers. – Stephan B Sep 01 '15 at 07:47
  • You can do this `new MemoryStream(myByteArray)` – Almis Sep 01 '15 at 07:48

2 Answers2

6

You can user a SqlDataReader.GetBytes to read data from the column or use SqlDataReader.GetSqlBytes or SqlDataReader.GetStream

Example :

Using getBytes

 SqlCommand command = new SqlCommand( .... );
 ...
 SqlDataReader sqlReader = command.ExecuteReader(CommandBehavior.SequentialAccess);
 byte[] outbyte = new byte[bufferSize]; 
 sqlReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

Using GetSqlBytes

 SqlCommand command = new SqlCommand( .... );
 ...
 SqlDataReader sqlReader = command.ExecuteReader(CommandBehavior.SequentialAccess);
 byte[] outbyte = sqlReader.GetSqlBytes(1).Buffer;
dvhh
  • 4,724
  • 27
  • 33
5

I believe You are searching for this:

SqlCommand command = new SqlCommand();
SqlDataReader reader = command.ExecuteReader();
System.IO.Stream stream = reader.GetStream(1); // 1 is the index of the column

GetStream method:

Retrieves binary, image, varbinary, UDT, and variant data types as a Stream.

ntohl
  • 2,067
  • 1
  • 28
  • 32