16

I'm trying to get a varbinary(MAX) from SQL Server to a byte[] variable in C#.

How can I do this?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ePezhman
  • 4,010
  • 7
  • 44
  • 80

2 Answers2

28
private static byte[] getDocument(int documentId)
{
    using (SqlConnection cn = new SqlConnection("..."))
    using (SqlCommand cm = cn.CreateCommand())
    {
        cm.CommandText = @"
            SELECT DocumentData
            FROM   Document
            WHERE  DocumentId = @Id";
        cm.Parameters.AddWithValue("@Id", documentId);
        cn.Open();
        return cm.ExecuteScalar() as byte[];
    }
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • 1
    Execute scalar returns a max of 2033 characters (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx). So this wouldn't work if your data was longer than 2033 bytes right? – Ian May 09 '17 at 20:25
1

You have to SELECT DATALENGTH(data) and data

where data is your varbinary(max)

int i=0;
long dataLen = dr.GetInt64(i++);
if (dataLen > 0)
{
    Data = new byte[dataLen];
    dr.GetBytes(i++, 0, Data, 0, (int)dataLen);
}
DiSaSteR
  • 608
  • 6
  • 11