I have a Dictionary object and I want to write to disk and be able to read it from disk. Ideally I would avoid any 3rd party libraries. Is there a simple way to do this with regular C# 4?
ANSWER ACCEPTED.
Summary:
OPTION 1 - Using JavaScriptSerializer
Pros: No 3rd party library necessary. Also, uses more modern format, i.e. JSON
Cons: Difficult to read -- not formated. Also, does require reference to less commonly used System.Web.Extension assembly, even when the application has nothing to do with the web.
Solution:
Write:
File.WriteAllText("SomeFile.Txt", new JavaScriptSerializer().Serialize(dictionary));
Read:
var dictionary = new JavaScriptSerializer()
.Deserialize<Dictionary<string, string>>(File.ReadAllText("SomeFile.txt"));
OPTION 2 - Using Linq to Xml
Pros: No 3rd party library necessary. Typically doesn't require adding additional references. Easily readable.
Cons: XML is not as preferable as something more modern such JSON.
Write:
new XElement("root", d.Select(kv => new XElement(kv.Key, kv.Value)))
.Save(filename, SaveOptions.OmitDuplicateNamespaces);
Read:
var dictionary = XElement.Parse(File.ReadAllText(filename))
.Elements()
.ToDictionary(k => k.Name.ToString(), v => v.Value.ToString());
OPTION 3 - Use JSON.NET
Pros: Human readable. Modern format.
Cons: 3rd party library necessary.
Solution:
Write:
File.WriteAllText("SomeFile.Txt", JsonConvert.SerializeObject(dictionary));
Read:
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>
(File.ReadAllText("SomeFile.txt"));