Example of using BinaryWriter, and BinaryReader to save a Dictionary<string,List<string>>:
using System.IO;
private Dictionary<string,List<string>> testDict = new Dictionary<string,List<string>>();
private string appPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"/dctStringString.bin";
private int itemsToCreate = 100000;
private int subListLength = 10;
private void btnTestDictionary_Click(object sender, EventArgs e)
{
List<string> valueList;
for (int i = 0; i < itemsToCreate; i++)
{
valueList = new List<string>();
for (int j = 0; j < subListLength; j++)
{
valueList.Add(j.ToString());
}
testDict.Add(i.ToString(), valueList);
}
dctSerialize(testDict, appPath);
Dictionary<string,List<string>> deSerializedDict = dctDeserialize(appPath);
}
public void dctSerialize(Dictionary<string,List<string>> dctToWrite, string appPath)
{
using (var writer = new BinaryWriter(File.Create(appPath)))
{
writer.Write(dctToWrite.Count);
writer.Write(subListLength);
foreach (var kvp in dctToWrite)
{
writer.Write(kvp.Key);
for (int i = 0; i < subListLength; i++)
{
writer.Write(kvp.Value[i]);
}
}
writer.Flush();
}
}
public Dictionary<string,List<string>> dctDeserialize(string appPath)
{
using (var reader = new BinaryReader(File.OpenRead(appPath)))
{
int itemsToRead = reader.ReadInt32();
int subListLength = reader.ReadInt32();
var dctToRead = new Dictionary<string,List<string>>(itemsToRead);
for (int n = 0; n < itemsToRead; n++)
{
string key = reader.ReadString();
List<string> value = new List<string>();
for (int i = 0; i < subListLength; i++)
{
value.Add(reader.ReadString());
}
dctToRead.Add(key, value);
}
return dctToRead;
}
}
This test generates a file with a million + 2 integers in it of about 2.46mb in size; if you zip the file, you can get it down to about 255k. Compressed with WinRar using standard settings yields a file under 70k.
It's on my list of things to do some day to polish this up and make it more "general purpose." Do things like making whether to write to a file, or memory, a parameter.
As you can see, if you start having generic Types as either Keys or Values in the Dictionary then you have to do some contortions; perhaps a
real generic-type-master could find a way around that ?
I use this for speed, adapting it as necessary.
The code was adapted based on the discussion of timing, and techniques shown here: [
^]; and, other sources that memory has been kind enough to erase :)
Disclaimer: If you use this code and cause famine, flood, power-grid failure, nuclear melt-down, plague epidemics, etc., please don't let me know, but if you find bugs, or see a better way to implement: I'm all ears !