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

旧巷老猫 提交于 2019-11-28 07:17:49

问题


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

How can I do this?

Thanks


回答1:


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[];
    }
}



回答2:


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);
}


来源:https://stackoverflow.com/questions/7724550/retrieve-varbinarymax-from-sql-server-to-byte-in-c-sharp

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