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

本秂侑毒 提交于 2019-11-29 13:27:07
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[];
    }
}

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!