I'm using this code for retrieving documents saved in Sql as binary. I'm getting this exception:
Invalid attempt to GetBytes on column ''. The GetBytes function can only be used on columns of type Text, NText, or Image.
What do I need to change?
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;
}
}
}
}
}
}
while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0)should bewhile ((readBytes = (int)dr.GetBytes(2, index, buffer, 0, size)) > 0)