简体   繁体   中英

How do I read and write a C# string Dictionary to a file?

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, ie 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"));

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<Dictionary<string, string>>(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<string, string> dictionary = new Dictionary<string, string>();
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<string, string> previousDictionary =
 JsonConvert.DeserializeObject<Dictionary<string, string>>
                                 (File.ReadAllText("SomeFile.txt"));

For comparison between the two options see: JSON.NET JsonConvert vs .NET JavaScriptSerializer

The simplest way to write Dictionary is to create a list of where every entry of the Dictionary is converted to an XElement. Then you create a root XElement where the list is the value of the root. The reason you want to use an XElement is because then you can use it's Save method to store it to disk as XML. Example doing that in a single line (where d is the Dictionary)

new XElement("root", d.Select(kv => new XElement(kv.Key, kv.Value)))
            .Save(filename, SaveOptions.OmitDuplicateNamespaces);

To read the file into a Dictionary, use the Parse static method of XElement and pass to it the entire contents of the file, which can read with File.ReadAllText . Parse returns an XElement object, the root. You can then iterate of the Elements() of the root and convert it to a Dictionary. You can do this in a single line:

var d = XElement.Parse(File.ReadAllText(filename))
                .Elements()
                .ToDictionary(k => k.Name.ToString(), v => v.Value.ToString());

Here's a version of the above wrapped in methods:

public static void Store(IDictionary<string, string> d, string filename)
{
    new XElement("root", d.Select(kv => new XElement(kv.Key, kv.Value)))
                .Save(filename, SaveOptions.OmitDuplicateNamespaces);
}
 public static IDictionary<string, string> Retrieve(string filename)
{
    return XElement.Parse(File.ReadAllText(filename))
                   .Elements()
                   .ToDictionary(k => k.Name.ToString(), v => v.Value.ToString());
}

An old thread, but I want to add an easy answer. For .net 5 and .netCore 3.0 and above you can simply use JsonSerializer. You just need your key and value to be serializable.

Write:

using System.Text.Json;
File.WriteAllText(fileName, JsonSerializer.Serialize(dictionary));

And to read:

JsonSerializer.Deserialize<Dictionary<string, string>>(fileName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM