Совместимы ли ядро ​​и инфраструктура BinaryFormatter Serialization dotnet? - PullRequest
0 голосов
/ 26 февраля 2019

У меня есть 2 программы, одна из которых написана на .Net Framework 4.7.x, а другая - в формате dot net core 2.1.

Программа 1, написанная на .Net Framework.берет набор данных и, используя BinaryFormatter, записывает его в поле базы данных в виде байта [].

Программа 2, написанная в ядре dot net, затем берет эту запись и пытается десериализовать поле, используя BinaryFormatter.Я получаю исключение «ArgumentException: тип« System.Byte »не десериализуем».

Программа 1

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;

    }

Программа 2

 static void Main(string[] args)
    {


        Console.WriteLine("Result_Cache_ID:");
        var reportIds = Console.ReadLine();
        if (int.TryParse(reportIds, out var resultCacheId))
        {

            GetDS(resultCacheId);
        }


        Console.ReadKey();
    }

    private static void GetDS(int resultCacheId)
    {

        using (var connection = new SqlConnection(ConnectionString))
        {
            connection.Open();

            using (var da = new SqlDataAdapter("Select * from Result_Cache where Result_Cache_ID="+ resultCacheId, connection))
            {
                var ds = new DataSet();
                da.Fill(ds);
                var binaryFormattedDs =(byte[]) ds.Tables[0].Rows[0]["Result_Binary_Data"];
                var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
                Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
            }

        }

    }

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

    }

я что-то не так делаю?

...