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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With