C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: Here you are asked to either Write the Dictionary and its contents to the file, or Read in a Dictionary from that file.
Console.ReadLineWrite: In Write, we use the using statement on a FileStream and BinaryWriter. We implement the simple file format described.
Read: In Read, we use a FileStream and BinaryReader and then loop through the required number of pairs.
C# program that reads and writes binary file for Dictionary
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
while (true)
{
Console.WriteLine("1=Write, 2=Read");
string value = Console.ReadLine();
if (value == "1")
{
var dictionary = new Dictionary<string, string>();
dictionary["Codex"] = "dot";
dictionary["net"] = "Codex";
dictionary["dot"] = "net";
Write(dictionary, "C:\\dictionary.bin");
}
else if (value == "2")
{
var dictionary = Read("C:\\dictionary.bin");
foreach (var pair in dictionary)
{
Console.WriteLine(pair);
}
}
}
}
static void Write(Dictionary<string, string> dictionary, string file)
{
using (FileStream fs = File.OpenWrite(file))
using (BinaryWriter writer = new BinaryWriter(fs))
{
// Put count.
writer.Write(dictionary.Count);
// Write pairs.
foreach (var pair in dictionary)
{
writer.Write(pair.Key);
writer.Write(pair.Value);
}
}
}
static Dictionary<string, string> Read(string file)
{
var result = new Dictionary<string, string>();
using (FileStream fs = File.OpenRead(file))
using (BinaryReader reader = new BinaryReader(fs))
{
// Get count.
int count = reader.ReadInt32();
// Read in all pairs.
for (int i = 0; i < count; i++)
{
string key = reader.ReadString();
string value = reader.ReadString();
result[key] = value;
}
}
return result;
}
}
Output
1=Write, 2=Read
1
1=Write, 2=Read
2
[Codex, dot]
[net, Codex]
[dot, net]
1=Write, 2=Read
Also: Performance reading in the file is good. It doesn't require much parsing. The reads are sequential and thus exploit the cache.
Note: Thanks to Paul Bright for suggesting an article that shows how to read and write a Dictionary to a binary file.
And: This solution could be adapted to more complex Dictionary types and optimized further.