How to write Dictionary to binary file in C#

1 Answer

0 votes
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            dictionary.Add("c#", 1);
            dictionary.Add("c", 2);
            dictionary.Add("c++", 3);
            dictionary.Add("java", 4);

            WriteDictionaryToBinFile(dictionary, "d:\\dictionary.bin");
        }
        static void WriteDictionaryToBinFile(Dictionary<string, int> dictionary, string file)
        {
            using (FileStream fs = File.OpenWrite(file))

            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                writer.Write(dictionary.Count);

                foreach (var kv in dictionary)
                {
                    writer.Write(kv.Key);
                    writer.Write(kv.Value);
                }
            }
        }
    }
}


/*
run:


*/

 



answered Mar 6, 2017 by avibootz
edited Mar 6, 2017 by avibootz

Related questions

1 answer 184 views
1 answer 186 views
1 answer 161 views
2 answers 221 views
2 answers 204 views
...