我有一个数据表,其中一列有图像文件路径。我需要用该图像的字节数组替换文件路径。下面的代码给了我错误。
数据源中String类型的给定值不能 转换为指定目标列的varbinary类型。
for (int rowIncrement = 0; rowIncrement < dt.Rows.Count; rowIncrement++)
{
byte[] photo = GetPhoto(dt.Rows[rowIncrement]["image"]);
dt.Rows[rowIncrement]["image"] = photo;
dt.AcceptChanges();
}
using (SqlBulkCopy copy = new SqlBulkCopy(sqlCon, SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.KeepIdentity, null))
{
copy.DestinationTableName = "UserDetails";
copy.WriteToServer(dt);
}
答案 0 :(得分:0)
应该指定列类型,否则当您需要byte []
时,columns值仍然是一个字符串示例:
// ADD a new column since you cannot change the type
dt.Columns.Add("image_tmp", typeof (byte[]));
for (int rowIncrement = 0; rowIncrement < dt.Rows.Count; rowIncrement++)
{
byte[] photo = GetPhoto(dt.Rows[rowIncrement]["image"]);
dt.Rows[rowIncrement]["image_tmp"] = photo;
dt.AcceptChanges();
}
// REMOVE image column and rename the temporary column
dt.Columns.Remove("image");
dt.Columns["image_tmp"].ColumnName = "image";