我有2个程序,一个用.Net Framework 4.7.x编写,另一个是点网核心2.1。
程序1,用.Net Framework编写。接受一个数据集,并使用BinaryFormatter将其作为字节[]写入数据库字段。
以点网核心编写的程序2,然后获取该记录,并尝试使用BinaryFormatter对字段进行反序列化。我收到异常“ ArgumentException:类型'System.Byte'无法反序列化。”
程序1
$minimum_cart_total = in_array('company', $roles) ? 250 : 100;
程序2
static void Main(string[] args)
{
var connectionString = ConfigurationManager.ConnectionStrings["CDPMetadataModelContext"].ConnectionString;
byte[] binaryFormattedDs;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var da = new SqlDataAdapter("Select * from Code_Job_Status", connection))
{
var ds = new DataSet();
da.Fill(ds);
binaryFormattedDs = SerializeBinaryDataContract(ds);
}
string query = "INSERT INTO dbo.Result_Cache (Result_Binary_Data, Run_DateTime) output inserted.Result_Cache_ID VALUES";
string insertQuery = "(@binaryValue, getdate())";
using (SqlCommand cmd = new SqlCommand(query + insertQuery, connection))
{
cmd.Parameters.AddWithValue("@binaryValue", SqlDbType.VarBinary).Value = binaryFormattedDs;
var newId = (int)cmd.ExecuteScalar();
Console.WriteLine("New Id= "+ newId);
Debug.WriteLine("New Id= " + newId);
}
connection.Close();
}
Console.ReadKey();
var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
Console.ReadKey();
}
public static T DeSerialize<T>(byte[] bytes)
{
var serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(ms);
}
}
public static byte[] SerializeBinaryDataContract(DataSet dataSet)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] buffer;
using (MemoryStream memoryStream = new MemoryStream())
{
dataSet.RemotingFormat = SerializationFormat.Binary;
binaryFormatter.Serialize((Stream)memoryStream, (object)dataSet);
buffer = new byte[memoryStream.Length];
memoryStream.Seek(0L, SeekOrigin.Begin);
memoryStream.Read(buffer, 0, buffer.Length);
}
return buffer;
}
我做错什么了吗?