Search code examples
c#dictionarybinaryfilesbinaryformatter

Save a dictionary to a binary file


I looked through another question asked here to get the code I tried.

So I have a dictionary here :

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

Suppose the dictionary is filled with employees with names and an identification code

and so I tried this to 'save it' using a binary file :

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

however, it seems this technique only works for objects.

here is the error that I get:

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

my goal is to simply retrieve the saved dictionary by reading the binary file. (if that is even possible?)


Solution

  • Updated.

    I think your first argument to your serializer is wrong. You're giving it a string of the path, and not the stream object. This works for me (BTW - removed relative path)

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