检索以二进制形式保存在Sql中的文档时出现异常-使用C#
我使用这段代码来检索以二进制形式保存在Sql中的文档。 我得到一个例外: 获取列“”上的字节的尝试无效。GetBytes函数只能用于Text、NText或Image类型的列 我需要改变什么检索以二进制形式保存在Sql中的文档时出现异常-使用C#,c#,sql,C#,Sql,我使用这段代码来检索以二进制形式保存在Sql中的文档。 我得到一个例外: 获取列“”上的字节的尝试无效。GetBytes函数只能用于Text、NText或Image类型的列 我需要改变什么 using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand())
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT fData.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(), fName FROM MyFsTable where fId = @fId";
DataGridViewRow row = this.DgDocuments.SelectedRows[0];
int id = (int)row.Cells["fId"].Value;
cmd.Parameters.Add("@fId", SqlDbType.Int).Value = id;
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
int size = 1024 * 1024;
byte[] buffer = new byte[size];
int readBytes = 0;
int index = 0;
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0)
{
fs.Write(buffer, 0, readBytes);
index += readBytes;
}
}
}
}
}
}
您可以使用下一行代码从varbinary列轻松获取字节数据
byte[] data = (byte[])reader[<your column name>];
字节[]数据=(字节[])读取器[];
除非我误解了您试图从实际数据块的路径(fData.PathName(),索引0)而不是数据本身(fData,索引2)tldr获取字节while((readBytes=(int)dr.GetBytes(0,索引,缓冲区,0,大小))>0)
应该是while((readBytes=(int)dr.GetBytes(2,索引,缓冲区,0,大小))>0)
@user1666620你说得对。。。谢谢