title: Storing C# Converted base64 as SQL Server varbinary(max)
body: <p>I've got an angular webapp where I accept images in base64 and store them in T-SQL varbinary. However, I have existing data stored in SQL-Server that appears to be in a different binary. I need both binaries to work with the same Read/Update methods in C#.</p>
  
  <p>In the service I'm trying to convert a base64 string to SQL Server's varbinary and vice versa.</p>
  
  <p>Manually in SSMS, I can take just the base64 string and insert into a row like this:</p>
  
  <pre><code>Cast(@base64ImgStr as varbinary(max))
  </code></pre>
  
  <p>But the result is different when I try to insert from C#:</p>
  
  <pre><code>Convert.FromBase64String(base64);
  </code></pre>
  
  <p>(same input). Since the binary is different the image doesn't show. I need a method in C# that provides the same binary as the one in T-SQL.</p>
  
  <p>I must be around the solution, since I can cast and get the proper base64 in SQL Server (again, not in C#) like this:</p>
  
  <pre><code>cast('' as xml).value('xs:base64Binary(sql:variable("@source"))', 'varchar(max)')
  </code></pre>
  
  <p>Instead of base64 I get back Unicode symbols, otherwise I'd paste in an example.</p>
  
  <p>I need to get the base64 without calling the SQL Server base64Binary method, because my service reads images like this:</p>
  
  <pre><code>Encoding.ASCII.GetString(varbinary)
  </code></pre>
  
  <p>If I convert the manually inserted varbinary (Cast(@base64ImgStr as varbinary(max))) into varchar(max), I get a base64 string and the image displays appropriately in my webapp.
  But, this is not so when I use the C# method to create the binary. With the type of varbinary I get from Convert.FromBase64String(base64), I need an intermediate conversion in SQL Server (xs:base64binary) to reverse the binary to base64. With no intermediate conversion I get Unicode symbols and no image displays in the webapp. I don't want an intermediate conversion because I want consistent results whether users upload images or someone inserts images manually. </p>
  
  <p>I don't see a method on the Convert class that gives me the same type of binary. But that seems to be exactly what I need. I suspect Unicode. Please help!</p>