1

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;
                            }
                        }
                    }
                }
            }
        }
2
  • 2
    Unless I misunderstand you're trying to get bytes from the path to the actual blob of data (fData.PathName(), index 0) rather than the data itself (fData, index 2) tldr; while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0) should be while ((readBytes = (int)dr.GetBytes(2, index, buffer, 0, size)) > 0) Commented Jan 21, 2016 at 15:28
  • @user1666620 You right... Thanks. Commented Jan 21, 2016 at 15:55

1 Answer 1

2

You can easy get bytes data from varbinary column using next line of code

byte[] data = (byte[])reader[<your column name>];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.