title: How to pass byte[] from C# as string to SQL Server stored procedure and convert into varbinary(MAX)
body: <p>In this project, there is a class which wraps ADO.NET for common data access like <code>ExecuteDataReader</code>, <code>ExecuteScalar</code>, etc..</p>
  
  <p>When using these methods to call a stored procedure, it allows you to pass a <code>Dictionary&lt;string, string&gt;</code> of parameters (string key, string value), which are then added to the <code>SqlCommand</code> object as <code>SqlParameter</code>.</p>
  
  <p>There is a case where we have to save a document in the database. The document is a <code>byte[]</code> and the corresponding column in the database is <code>varbinary(MAX)</code>.</p>
  
  <p>We've looked around for a solution but all that is available are examples using <code>SqlDbType.Varbinary</code>, which is not an option in this situation.</p>
  
  <p>Our latest attempt was to attempt to convert the <code>byte[]</code> to a binary string, pass it into the stored procedure as <code>nvarchar(max)</code>, and then use <code>CONVERT(varbinary(max), @theFileBinaryString)</code> when saving it to the <code>Document</code> table, however, this saves a corrupt file. </p>
  
  <p>C#</p>
  
  <pre><code>byte[] pDocumentBytes = ...;
  string documentAsBinary = "0x" + BitConverter.ToString(pDocumentBytes).Replace("-", ""); 
  </code></pre>
  
  <p>SQL</p>
  
  <pre><code>@DocumentContentAsBinary nvarchar(max) -- This is "documentAsBinary" from C# above
  
  DECLARE @DocumentContentVarbinary varbinary(max);
  SET @DocumentContentVarbinary = CONVERT(varbinary(max), @DocumentContentAsBinary);
  </code></pre>