Сохранить словарь в двоичный файл

Я просмотрел другой вопрос, заданный здесь, чтобы получить код, который я пробовал.

Итак, у меня есть словарь здесь:

private static Dictionary<int, string> employees = new Dictionary<int, string>();
//the int key is for the id code, the string is for the name 

Предположим, что словарь заполнен сотрудниками с именами и идентификационным кодом

и поэтому я попробовал это, чтобы «сохранить» с помощью двоичного файла:

        FileStream binaryfile = new FileStream(@"..\..\data\employees.bin", FileMode.OpenOrCreate);

        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(@"..\..\data\employees.bin", employees);

        binaryfile.Close();

однако кажется, что этот метод работает только для объектов.

вот ошибка, которую я получаю:

The best overloaded method match for 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream, object)' has some invalid arguments

моя цель - просто получить сохраненный словарь, прочитав двоичный файл. (если это вообще возможно?)


person redwa11    schedule 07.05.2016    source источник
comment
Думали ли вы, что один из ваших аргументов в пользу binayFormatter.Serialize может быть неверным?   -  person yaakov    schedule 08.05.2016


Ответы (1)


Обновлено.

Я думаю, что ваш первый аргумент вашему сериализатору неверен. Вы даете ему строку пути, а не объект потока. Это работает для меня (кстати - удален относительный путь)

class Program
{
    private static Dictionary<int, string> employees = new Dictionary<int, string>();
    static void Main(string[] args)
    { 
        employees.Add(1, "Fred");
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        var fi = new System.IO.FileInfo(@"employees.bin");

        using (var binaryFile = fi.Create())
        {
            binaryFormatter.Serialize(binaryFile, employees);
            binaryFile.Flush();
        }

        Dictionary<int, string> readBack;
        using (var binaryFile = fi.OpenRead())
        {
              readBack = (Dictionary < int, string> )binaryFormatter.Deserialize(binaryFile);
        }

        foreach (var kvp in readBack)
            Console.WriteLine($"{kvp.Key}\t{kvp.Value}");
    }
}
person Wesley Long    schedule 07.05.2016