如何将C#字符串字典读取和写入文件? [英] How do I read and write a C# string Dictionary to a file?

查看:587
本文介绍了如何将C#字符串字典读取和写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary对象,我想写入磁盘并能够从磁盘读取它.理想情况下,我会避免使用任何第三方库.使用常规C#4可以简单地做到这一点吗?

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.

摘要:

选项1-使用JavaScriptSerializer

优点:不需要第三方库.另外,使用更现代的格式,即JSON

Pros: No 3rd party library necessary. Also, uses more modern format, i.e. JSON

缺点:难以阅读-未格式化.而且,即使应用程序与Web无关,也确实需要引用不太常用的System.Web.Extension程序集.

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.

解决方案:

写:

File.WriteAllText("SomeFile.Txt", new JavaScriptSerializer().Serialize(dictionary));

阅读:

var dictionary = new JavaScriptSerializer()
    .Deserialize<Dictionary<string, string>>(File.ReadAllText("SomeFile.txt"));

选项2-使用Linq进行Xml

优点:不需要第三方库.通常不需要添加其他引用.易于阅读.

Pros: No 3rd party library necessary. Typically doesn't require adding additional references. Easily readable.

缺点: XML不如更现代的JSON这样可取.

Cons: XML is not as preferable as something more modern such JSON.

写:

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

阅读:

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

选项3-使用JSON.NET

优点:易于阅读.现代格式.

Pros: Human readable. Modern format.

缺点:需要第三方库.

解决方案:

写:

File.WriteAllText("SomeFile.Txt", JsonConvert.SerializeObject(dictionary));

阅读:

var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>
    (File.ReadAllText("SomeFile.txt"));

推荐答案

编写Dictionary的最简单方法是创建一个列表,其中列出Dictionary的每个条目都转换为XElement的位置.然后,创建一个根XElement,其中列表是根的值.您想要使用XElement的原因是因为您可以使用它的Save方法将其作为XML存储到磁盘.单行执行此操作的示例(其中d是Dictionary)

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);

要将文件读入字典,请使用XElement的Parse静态方法,并将文件的全部内容传递给该文件,该文件可以用File.ReadAllText读取.解析返回一个XElement对象,即根.然后,您可以迭代根的Elements()并将其转换为Dictionary.您可以在一行中完成此操作:

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());
}

这篇关于如何将C#字符串字典读取和写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆