Raskaroth
Raskaroth

Reputation: 659

c#/asp.net show binary data from database

I have been searching for how to retrieve binary data from the database. My query is working fine as it shows the binary data in the SQL manager.

But in Visual Studio 2010 it just shows me <Binary Data>, which I personally think is not the problem, but if I try to retrieve it and store it in a variable it's just empty. Any other query works as long as it has nothing to do with binary data...

And I don't want to use a datagrid or anything as I only need it as a variable.

SqlCommand CMDbinary = new SqlCommand("SELECT Binary_field AS binary "
                                      + "FROM BIN_table", abc_conn);

SqlDataReader Bin_retriever = CMDbinary.ExecuteReader();
while (Bin_retriever.Read())
{
    BIN.Add(Bin_retriever["binary"].ToString());
}
abc_conn.Close();

I know this is not the full code, but this is where it goes wrong, I assume I have to do something special in order to display binary info, as (I'll say it again) it works if I change Binary_field to UID (which is a varchar in the database).

Any help on this would be really welcome, Thanks in advance!

Upvotes: 2

Views: 1655

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062745

 Bin_retriever["binary"].ToString()

looks deadly. For binary data you can expect to get byte[] here. You can't just call ToString() on such - you'll probably get the type name. So, how would you want to display it? hex?

byte[] raw = (byte[]) Bin_retriever["binary"];

now format as you choose. For example:

var builder = new StringBuilder(raw.Length * 2);
for(int i = 0 ; i < raw.Length ; i++)
    builder.Append(raw[i].ToString("x2"));
string hex = builder.ToString();

Upvotes: 3

Related Questions