简体   繁体   中英

How can I use SqlBulkCopy with binary data (byte[]) in a DataTable?

I'm trying to use SqlBulkCopy to import a bunch of data to our website. In most of the other areas we're using Entity model which uses byte arrays to represent binary data in SQL. However, SqlBulkCopy seems to be confusing byte[] with string. Everything seems to be working fine except for this one binary column which throws an exception: "The given value of type String from the data source cannot be converted to type binary of the specified target column."

I've created a small test case to illustrate the problem:

using System.Data;
using System.Data.SqlClient;

namespace SqlBulkCopyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable table = new DataTable("BinaryData");
            table.Columns.Add("Data");

            for (int i = 0; i < 10; i++)
            {
                var row = table.NewRow();
                row["Data"] = new byte[5] { 1, 2, 3, 4, 5 };
                table.Rows.Add(row);
            }

            using (var connection = 
                new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=TestBulkCopy;Integrated Security=True"))
            {
                connection.Open();
                using (var copier = new SqlBulkCopy(connection))
                {
                      copier.DestinationTableName = table.TableName;
/* EXCEPTION HERE: */ copier.WriteToServer(table);
                }
            }
        }
    }
}

This uses a test database with a BinaryData table which has a single binary(5) column named Data .

Any help would be greatly appreciated

Instead of:

table.Columns.Add("Data");

Add the "Data" column as a binary:

table.Columns.Add("Data", typeof(Byte[]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM