如何将C#中的byte 作为字符串传递给SQL Server存储过程并转换为varbinary(MAX)

在这个项目中,有一个包装ADO.NET以进行常见数据访问的类,如ExecuteDataReaderExecuteScalar等。

使用这些方法调用存储过程时,它允许您传递Dictionary参数(字符串键,字符串值),然后将其作为SqlParameter添加到SqlCommand对象中。

有一种情况我们必须在数据库中保存文档。 该文档是byte[] ,数据库中的相应列是varbinary(MAX)

我们已经四处寻找解决方案,但所有可用的都是使用SqlDbType.Varbinary示例,在这种情况下这不是一个选项。

我们最近的尝试是尝试将byte[]转换为二进制字符串,将其作为nvarchar(max)传递给存储过程,然后在将其保存到Document表时使用CONVERT(varbinary(max), @theFileBinaryString) ,但是,这会保存损坏的文件。

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

假设你有这个SP:

 DECLARE @Value1 ... @Value2 ... ... @File VARBINARY(MAX) INSERT INTO [YourTable] (Column1, Column2, ..., File) VALUES (@Value1, @Value2, ..., @File) 

使用此语法将文件转换为字节数组,并直接将字节数组作为varbinary数据插入:

 using System.Data.SqlClient; using System.IO; byte[] data; using (FileStream fs = new FileStream(document, FileMode.Open) { BinaryReader fileReader = new BinaryReader(document); data = fileReader.ReadBytes((int)document.Length); document.Close(); // don't forget to close file stream } using (var connection = new SqlConnection("YourConnectionStringHere")) { connection.Open(); using (var command = new SqlCommand("YourSPHere", connection) { command.CommandType = CommandType.StoredProcedure; // insert parameters here // add file parameter at the end of collection parameters command.Parameters.AddWithValue("@File", SqlDbType.VarBinary).Value = data; command.ExecuteNonQuery(); } connection.Close(); } 

参考: http : //www.codeproject.com/Questions/309795/How-to-insert-byte-array-into-SQL-table

我希望这个解决方案有用。

更新您的查询以使用参数并将字节数组作为参数直接传递给表

例如SQL:

 insert into table values (@data); 

C#

 SqlComman com = new SqlCommand("insert into table values (@data);",Database Connection); com.Paramaters.Add(new SqlParameter("@Data" Byte array)); com.executeNonQuery(); 

VARBINARY(MAX)byte[]之间没有正确映射的SqlDbType 。 但实际上这没关系,因为参数化基础设施只是为你处理这个问题,下面的代码就可以了:

 var binary = new bytes[1]; var command = new SqlCommand("INSERT INTO [MyTable]([BinaryColumn]) VALUES (@binary)"); command.Parameters.AddWithValue("@binary", binary); command.ExecuteNonQuery(); 

有关更多详细信息,请参见此处: SqlDbType映射到varBinary(max)的内容是什么?