Convert SQL binary(64) to byte[]

How to convert SQL binary(64) to byte[] in C# using SqlReader?
sepknowAsked:
Who is Participating?
 
discon0Commented:
Here's how to do it using GetBytes()

      byte[] data = new byte[64];            // Allocate 64 bytes
      dtr.GetBytes(
            dtr.GetOrdinal("data"),            // Column ordinal (index)
            0,                                          // start reading at byte 0
            data,                                    // write to the 'data' array
            0,                                          // start writing at index 0 inside 'data'
            64);                                    // 64 bytes

You can also use the way I've shown before:
      byte[] data = (byte[])dtr["data"];  // Use this only if the 'data' column can't be null

      byte[] data = dtr["data"] as byte[]; // Use this either way
0
 
surajgupthaCommented:
Can you be more specific about what you want? A little more detail will help.
0
 
discon0Commented:
Assuming you have a table with a column 'id' (integer) and a column 'data' (binary(64)), the following example reads each row sequentially and shows it in a message box:

                  using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
                  {
                        con.Open();

                        SqlCommand cmd = new SqlCommand("SELECT * from bindata", con);
                        using (SqlDataReader dtr = cmd.ExecuteReader())
                        {
                              while (dtr.Read())
                              {
                                    int id = (int)dtr["id"];
                                    byte[] data = (byte[])dtr["data"];

                                    MessageBox.Show(string.Format("{0} = {1}",
                                          id,
                                          System.Text.Encoding.UTF8.GetString(data)));
                              }
                        }
                  }
0
 
sepknowAuthor Commented:
Hi surajguptha,
Let me re-phrase:
How to read a SQL column of datatype binary(64) using SqlReader?

discon0 solution is close to what I want.
To discon, how to retrieve using GetBytes()?


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.