Kliver Max
Kliver Max

Reputation: 5299

How to read blob from SQL Server?

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[]?

Upvotes: 1

Views: 6312

Answers (2)

dvhh
dvhh

Reputation: 4750

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;

Upvotes: 6

ntohl
ntohl

Reputation: 2125

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.

Upvotes: 5

Related Questions