Retrieve varbinary(MAX) from SQL Server to byte[]

2020-02-13 08:03发布

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

How can I do this?

Thanks

2条回答
聊天终结者
2楼-- · 2020-02-13 08:44

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);
}
查看更多
一夜七次
3楼-- · 2020-02-13 08:56
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[];
    }
}
查看更多
登录 后发表回答