Search code examples
c#sqlarraysvarbinary

How to read varbinary of SQL as string in C#?


I have an web application which reads varbinary from SQL as a byte array in code. Basically it does a ExecuteScalar of the column and returns it as a byte array.

I am now doing a mini version of the application as a Windows application. For this, I am trying to skip the DB connection. I am directly inputting the varbinary value from SQL to a RichTextBox and trying to read it as a byte array. However, I do not get the same byte array. What am I doing wrong and how should I proceed ?


Solution

  • I got it using this piece of code

        string hex = richTextBox1.Text
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2).ToString(), 16);
        return bytes;