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

后端 未结 2 1602
日久生厌
日久生厌 2021-02-06 11:18

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

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 11:25

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

提交回复
热议问题