C # BinaryFormatter. Не удалось выполнить сериализацию с исключением - PullRequest
0 голосов
/ 15 октября 2019

Я попробовал пример кода в Метод BinaryFormatter.Deserialize , когда я отлаживаю в Visual Studio, результат будет таким, как ожидалось. Хотя, когда я выполняю exe-файл непосредственно в папке отладки, он получает исключение «конец потока обнаружен до завершения анализа».

Это происходит только тогда, когда я устанавливаю целевую платформу проекта на ".NET Framework 4.8" или версию 4.7. как показано ниже: enter image description here Сообщение об ошибке: enter image description here

Еще более странно, что это происходит только при использовании версий 4.7 и 4.8. Если я перейду на версию .net 4.0, эта проблема исчезнет и даже переключится обратно на .net 4.7 и 4.8. Это больше не случится.

Похоже, что в более поздней версии .net для "BinaryFormatter.Deserialize" отсутствуют некоторые зависимости? Баги для .net framework? Кто-нибудь знает, как решить эту проблему?

Также запишите видео для этой проблемы: https://www.screencast.com/t/nC38Sm3q3pVQ

Код, как показано ниже:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

public class App 
{
[STAThread]
static void Main() 
{
    Serialize();
    Deserialize();

    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}

static void Serialize() 
{
    // Create a hashtable of values that will eventually be serialized.
    Hashtable addresses = new Hashtable();
    addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
    addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
    addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

    // To serialize the hashtable and its key/value pairs,  
    // you must first open a stream for writing. 
    // In this case, use a file stream.
    FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

    // Construct a BinaryFormatter and use it to serialize the data to the stream.
    BinaryFormatter formatter = new BinaryFormatter();
    try 
    {
        formatter.Serialize(fs, addresses);
    }
    catch (SerializationException e) 
    {
        Console.WriteLine("Failed to serialize. Reason: " + e.Message);
        throw;
    }
    finally 
    {
        fs.Close();
    }
}


static void Deserialize() 
{
    // Declare the hashtable reference.
    Hashtable addresses  = null;

    // Open the file containing the data that you want to deserialize.
    FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
    try 
    {
        BinaryFormatter formatter = new BinaryFormatter();

        // Deserialize the hashtable from the file and 
        // assign the reference to the local variable.
        addresses = (Hashtable) formatter.Deserialize(fs);
    }
    catch (SerializationException e) 
    {
        Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
        throw;
    }
    finally 
    {
        fs.Close();
    }

    // To prove that the table deserialized correctly, 
    // display the key/value pairs.
    foreach (DictionaryEntry de in addresses) 
    {
        Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
    }
}
}

Спасибо,

1 Ответ

0 голосов
/ 15 октября 2019

Вот код, который я запустил как консольное приложение. Единственное отличие состоит в том, что я добавил console.readkey, чтобы я мог просмотреть вывод. Это было 4.8 в vs2019, AnyCpu для конфигурации. Как я уже сказал, он работал в режиме отладки и из папки в одиночку.

using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp1
{
 class Program
 {
    [STAThread]
    static void Main()
    {
        Serialize();
        Deserialize();

        Console.ReadKey();
    }

    static void Serialize()
    {
        // Create a hashtable of values that will eventually be serialized.
        Hashtable addresses = new Hashtable();
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable and its key/value pairs,  
        // you must first open a stream for writing. 
        // In this case, use a file stream.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        // Construct a BinaryFormatter and use it to serialize the data to the stream.
        BinaryFormatter formatter = new BinaryFormatter();
        try
        {
            formatter.Serialize(fs, addresses);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }


    static void Deserialize()
    {
        // Declare the hashtable reference.
        Hashtable addresses = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();

            // Deserialize the hashtable from the file and 
            // assign the reference to the local variable.
            addresses = (Hashtable)formatter.Deserialize(fs);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }

        // To prove that the table deserialized correctly, 
        // display the key/value pairs.
        foreach (DictionaryEntry de in addresses)
        {
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
        }
    }
 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...