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

时间:2010-06-18 04:57:04

标签: c# linq dictionary

我有一个Dictionary

类型的字典对象

并尝试使用StreamWriter将整个内容输出到文本文件,但未能从Dictionary类中找到正确的方法。

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

        }

我只能检索第一个元素,它还有一个方括号和中间的逗号分隔符:

[Peter,Admin]

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

7 个答案:

答案 0 :(得分:33)

File.WriteAllLines("myfile.txt",
    dictionary.Select(x => "[" + x.Key + " " + x.Value + "]").ToArray());

(如果你使用的是.NET4,那么你可以省略最后的ToArray电话。)

答案 1 :(得分:28)

您需要自己遍历这些条目:

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

答案 2 :(得分:3)

foreach (KeyValuePair<string,string>  kvp in dictionary)
{
     System.IO.File.AppendAllText("dictionary.txt", string.Format("{0} {1} {2}", kvp.Key,    kvp.Value, Environment.NewLine));
}

答案 3 :(得分:2)

File.WriteAllLines("myfile.txt",dictionary.Select(s=>s.ToString());

应该这样做,因为字典元素的ToString函数被定义为将每个元素以下列格式放在文本文件中。

[key1,Value1]
[key2,Value2]
.
.

答案 4 :(得分:1)

您需要选择要编写的字符串,并迭代生成的枚举以写入每一行:

var dataToWrite = from kvp in dictionary
                  select String.Format("[{0} {1}"], kvp.Key kvp.Value);

using (StreamWriter sw = new StreamWriter("myfile.txt"))
{
    foreach (string dataLine in dataToWrite)
    {
        sw.WriteLine(dataLine);
    }
}

答案 5 :(得分:1)

var pairs = from p in yourDictionary.Keys
    select new {Key=p, Value=yourDictionary[p]};

foreach(var pair in pairs)
    yourStreamWriter.WriteLine("Key={0}, Value={1}", pair.Key, pair.Value);

答案 6 :(得分:1)

// Demonstration
private void WriteDictToFile(Dictionary<string, string> someDict) 
{
    using (StreamWriter fileWriter = new StreamWriter("PATH\\TO\\FILE.txt")
    {
        // You can modify <string, string> notation by placing your types.
        foreach (KeyValuePair<string, string> kvPair in someDict) 
        {
            fileWriter.WriteLine("{0}: {1}", kvPair.Key, kvPair.Value);
        }
        fileWriter.Close();
    }
}

并在Main中使用

static void Main(string[] args) 
{
    Dictionary<string, string> dataDict = new Dictionary<string, string>();
    Console.Write("Enter your name: ");
    string n = Console.ReadLine();
    Console.Write("Enter your surname: ");
    string s = Console.ReadLine();
    dataDict.Add("Name", n)
    dataDict.Add("Surname", s)
    WriteDictToFile(dataDict);
}