C # storage converted base64 as varbinary SQL Server (max)

I have an angular webapp where I take base64 images and store them in varbinary T-SQL. However, I have existing data stored in SQL-Server that appears to be in a different binary format. I need both binaries to work with the same read / update methods in C #.

In a service, I am trying to convert a base64 string to a varbinary SQL Server and vice versa.

In manual mode in SSMS I can only take the base64 string and insert into the string like this:

Cast(@base64ImgStr as varbinary(max))

      

But when trying to insert from C #, the result is different:

Convert.FromBase64String(base64);

      

(same input). Because the binary is different, no image is displayed. I need a method in C # that provides the same binary as in T-SQL.

I have to be around the solution, as I can use and get the base64 I want in SQL Server (again, not C #) like this:

cast('' as xml).value('xs:base64Binary(sql:variable("@source"))', 'varchar(max)')

      

Instead of base64, I am returning Unicode characters, otherwise I would insert an example.

I need to get base64 without calling the base64Binary method of SQL Server because my service reads images like this:

Encoding.ASCII.GetString(varbinary)

      

If I convert the manually entered varbinary (Cast (@ base64ImgStr as varbinary (max))) to varchar (max), I get the base64 string and the image is displayed accordingly in my webapp. But this is not the case when I use the C # method to create the binary. With varbinary type I get from Convert.FromBase64String (base64), I need intermediate conversion in SQL Server (xs: base64binary) to reverse the binary to base64. Without intermediate conversion, I am getting Unicode characters and no images are displayed in the webapp. I don't want an intermediate conversion because I want consistent results whether users are uploading images or someone is inserting images manually.

I don't see a method on the Convert class that gives me the same type of binary. But this looks like what I need. I suspect Unicode. Please, help!

+3


source to share


1 answer


This worked for me:

var image = Convert.FromBase64String(base64);
string hex = BitConverter.ToString(image);
hex = hex.Replace("-", "");
hex = "0x" + hex;

      



This hex can be saved in the field varbinary(MAX)

without casting or transforming and will display as an image in the browser.

0


source







All Articles