Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varbinary text representation to byte[]

Tags:

c#

sql-server

In C#, how can I take the textual output that SQL Server Management Studio shows as the contents of a varbinary column, and turn that text into the byte[] that is stored in the column?

like image 761
Slaggg Avatar asked Sep 27 '11 00:09

Slaggg


2 Answers

OK, so you want to copy and paste the value displayed in SSMS for a varbinary column (e.g. "0x6100730064006600"), and get the byte[] from it in C#?

That's quite easy - the part after 0x is just hex values (2 characters each). So, you take each pair, convert it to a number specifying a base of 16 (hex), and add it to a list, like so:

string stringFromSQL = "0x6100730064006600";
List<byte> byteList = new List<byte>();

string hexPart = stringFromSQL.Substring(2);
for (int i = 0; i < hexPart.Length / 2; i++)
{
    string hexNumber = hexPart.Substring(i * 2, 2);
    byteList.Add((byte)Convert.ToInt32(hexNumber, 16));
}

byte [] original = byteList.ToArray();

Disclaimer - fairly dodgy and unoptimal code, I just hacked it together for demonstration purposes (it should work though).

like image 61
Daniel B Avatar answered Nov 08 '22 00:11

Daniel B


    SqlConnection conn = new SqlConnection(yourConnectionString);
    SqlCommand cmd = new SqlCommand("select col from yourtable", conn);
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.HasRows)
    {
        byte[] bytes = (byte[])reader[0];
    }
    reader.Close();
    conn.Close();
like image 6
ojlovecd Avatar answered Nov 08 '22 02:11

ojlovecd