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