Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting SQL Server varBinary data into string C#

Tags:

I need help figuring out how to convert data that comes in from a SQL Server table column that is set as varBinary(max) into a string in order to display it in a label.

This is in C# and I'm using a DataReader.

I can pull the data in using:

var BinaryString = reader[1]; 

i know that this column holds text that was previously convert to binary.

like image 954
PercivalMcGullicuddy Avatar asked Feb 10 '11 15:02

PercivalMcGullicuddy


People also ask

Is Varbinary a string?

Store raw-byte data, such as IP addresses, up to 65000 bytes. The BINARY and BINARY VARYING (VARBINARY) data types are collectively referred to as binary string types and the values of binary string types are referred to as binary strings. A binary string is a sequence of octets or bytes.

What is Varbinary data type in SQL Server?

The VARBINARY type is similar to the VARCHAR type, but stores binary byte strings rather than non-binary character strings. M represents the maximum column length in bytes. It contains no character set, and comparison and sorting are based on the numeric value of the bytes.


2 Answers

It really depends on which encoding was used when you originally converted from string to binary:

 byte[] binaryString = (byte[])reader[1];   // if the original encoding was ASCII  string x = Encoding.ASCII.GetString(binaryString);   // if the original encoding was UTF-8  string y = Encoding.UTF8.GetString(binaryString);   // if the original encoding was UTF-16  string z = Encoding.Unicode.GetString(binaryString);   // etc 
like image 56
LukeH Avatar answered Sep 19 '22 08:09

LukeH


The binary data must be encoded text - and you need to know which encoding was used in order to accurately convert it back to text. So for example, you might use:

byte[] binaryData = reader[1]; string text = Encoding.UTF8.GetString(binaryData); 

or

byte[] binaryData = reader[1]; string text = Encoding.Unicode.GetString(binaryData); 

or various other options... but you need to know the right encoding. Otherwise it's like trying to load a JPEG file into an image viewer which only reads PNG... but worse, because if you get the wrong encoding it may appear to work for some strings.

The next thing to work out is why it's being stored as binary in the first place... if it's meant to be text, why isn't it being stored that way.

like image 21
Jon Skeet Avatar answered Sep 20 '22 08:09

Jon Skeet