如何将字典的内容写入文本文件

如何将字典的内容写入文本文件

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

问题描述

我有一个类型为Dictionary的字典对象



,并尝试使用StreamWriter将整个内容输出到文本文件,但无法从字典中找到正确的方法使用(StreamWriter sw = new StreamWriter(myfile.txt))
$ {


$ sw.WriteLine(dictionary.First());

}

我只能检索第一个元素,它被一个方括号加上一个逗号分隔符之间:



[Peter,Admin]



很高兴有[Peter Admin](没有逗号)

解决方案

您需要自行循环输入:

  using(StreamWriter file = new StreamWriter(myfile.txt))
foreach(字典中的var项)
file.WriteLine([{0} {1}],entry.Key,entry.Value);


I have a dictionary object of type Dictionary

and trying to use StreamWriter to output the entire content to a text file but failed to find the correct method from the Dictionary class.

using (StreamWriter sw = new StreamWriter("myfile.txt"))
        {
            sw.WriteLine(dictionary.First());

        }

I can only retrieve the first element and it is bounded by a square bracket plus a comma separator in between as well:

[Peter, Admin]

and would be nice to have [Peter Admin] (without the comma)

解决方案

You need to loop over the entries yourself:

using (StreamWriter file = new StreamWriter("myfile.txt"))
    foreach (var entry in dictionary)
        file.WriteLine("[{0} {1}]", entry.Key, entry.Value);

这篇关于如何将字典的内容写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 15:07