title: How do I read and write a C# string Dictionary to a file?
body: <p>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?</p>
  
  <p><strong><em>ANSWER ACCEPTED.</em></strong></p>
  
  <p>Summary:</p>
  
  <p><strong>OPTION 1 - Using JavaScriptSerializer</strong></p>
  
  <p><em>Pros:</em> No 3rd party library necessary.  Also, uses more modern format, i.e. JSON</p>
  
  <p><em>Cons:</em> 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.</p>
  
  <p><em>Solution:</em></p>
  
  <p>Write:</p>
  
  <pre><code>File.WriteAllText("SomeFile.Txt", new JavaScriptSerializer().Serialize(dictionary));
  </code></pre>
  
  <p>Read:</p>
  
  <pre><code>var dictionary = new JavaScriptSerializer()
      .Deserialize&lt;Dictionary&lt;string, string&gt;&gt;(File.ReadAllText("SomeFile.txt"));
  </code></pre>
  
  <p><strong>OPTION 2 - Using Linq to Xml</strong></p>
  
  <p><em>Pros:</em> No 3rd party library necessary.  Typically doesn't require adding additional references.  Easily readable.</p>
  
  <p><em>Cons:</em> XML is not as preferable as something more modern such JSON.</p>
  
  <p>Write:</p>
  
  <pre><code>new XElement("root", d.Select(kv =&gt; new XElement(kv.Key, kv.Value)))
              .Save(filename, SaveOptions.OmitDuplicateNamespaces);
  </code></pre>
  
  <p>Read:</p>
  
  <pre><code>var dictionary = XElement.Parse(File.ReadAllText(filename))
                  .Elements()
                  .ToDictionary(k =&gt; k.Name.ToString(), v =&gt; v.Value.ToString());
  </code></pre>
  
  <p><strong>OPTION 3 - Use JSON.NET</strong></p>
  
  <p><em>Pros:</em> Human readable.  Modern format.</p>
  
  <p><em>Cons:</em> 3rd party library necessary.</p>
  
  <p><em>Solution:</em></p>
  
  <p>Write:</p>
  
  <pre><code>File.WriteAllText("SomeFile.Txt", JsonConvert.SerializeObject(dictionary));
  </code></pre>
  
  <p>Read:</p>
  
  <pre><code>var dictionary = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, string&gt;&gt;
      (File.ReadAllText("SomeFile.txt"));
  </code></pre>