Search code examples
c#sql-serverstringbinary-datatype-conversion

Convert string stored as binary back to string


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[]"


Solution

  • 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);