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
Without a Third Party like JSON.Net, Use JavaScriptSerializer:
File.WriteAllText("SomeFile.Txt", new JavaScriptSerializer().Serialize(dictionary));
Getting dictionary back from file:
var dictionary = new JavaScriptSerializer()
.Deserialize>(File.ReadAllText("SomeFile.txt"));
Only thing to remember is to add reference to System.Web.Extensions
under project references and then you will be able to use JavaScriptSerializer
after using System.Web.Script.Serialization;
Or with JSON.Net you can serialize your dictionary to JSON and then write it to file and then deserialize it, like:
Dictionary dictionary = new Dictionary();
dictionary.Add("1", "Some value 1");
dictionary.Add("2", "Something");
Storing Dictionary in file:
string json = JsonConvert.SerializeObject(dictionary);
File.WriteAllText("SomeFile.Txt", json);
Getting Dictionary back from file:
Dictionary previousDictionary =
JsonConvert.DeserializeObject>
(File.ReadAllText("SomeFile.txt"));
For comparison between the two options see: JSON.NET JsonConvert vs .NET JavaScriptSerializer