1

I have stored string as binary data in db.
I am loading this data into c# as byte[]. How do I convert it to original string there?

declare @QRCodeLink nvarchar(max) = 'goo.gl/JCKW'
declare @QRCodeData varbinary(max) = CONVERT(varbinary(max), @QRCodeLink)
UPDATE dbo.QRCode
SET QRCodeData = @QRCodeData
WHERE ID = @ID

In C# code, Convert.ToString(qrCodeData) results in this "System.Byte[]"

3 Answers 3

3

The nvarchar value is converted to a binary value where each character is two bytes.

You can convert it already when you read it from the database:

select convert(nvarchar(max), QRCodeData) from dbo.QRCode ...

Or you can use the UTF-16 encoding to convert the data in C#:

string qrCodeLink = Encoding.Unicode.GetString(qrCodeData);
Sign up to request clarification or add additional context in comments.

Comments

1

Use Encoding.GetString()

byte[] byteArr = Encoding.UTF8.GetBytes("hello");
string s = Encoding.UTF8.GetString(byteArr);
Console.WriteLine(s);

1 Comment

I am getting the byte[] from db. Encoding.UTF8.GetString gives me the string with \0 between every char.
0

It depends on the string encoding but assuming you are using ASCII

string decoded = ASCIIEncoding.ASCII.GetString(byteArray);

Where byteArray is your data from sqlserver

If it returns garbage try UTF8 or other encodings

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.