【问题标题】:How to write the content of a dictionary to a text file?如何将字典的内容写入文本文件?
【发布时间】:2011-03-05 06:45:46
【问题描述】:

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

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

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

        }

我只能检索第一个元素,它由方括号加上逗号分隔符限定:

[彼得,管理员]

如果有 [Peter Admin](不带逗号)会很高兴

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我的同事指出我可以这样做... foreach(KeyValuePair entry in dictionary) sw.WriteLine(entry.Key + entry.Value);跨度>
    【解决方案2】:

    您需要选择要编写的字符串,然后遍历生成的枚举以编写每一行:

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

    【讨论】:

      【解决方案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));
      }
      

      【讨论】:

      • +1 因为我正在重写采用 Lists 来代替 Dictionaries 的方法,我真的想继续使用静态 File 类方法。但后来我意识到这会在每次迭代时打开和关闭文件,这可能不是一个好主意。
      【解决方案4】:
      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);
      

      【讨论】:

        【解决方案5】:
        File.WriteAllLines("myfile.txt",
            dictionary.Select(x => "[" + x.Key + " " + x.Value + "]").ToArray());
        

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

        【讨论】:

        • 我还建议将其作为扩展方法。
        • csv 样式:File.WriteAllLines("myfile.txt", dictionary.Select(s => String.Format("{0};{1}", s.Key, s.Value) ));
        【解决方案6】:
        File.WriteAllLines("myfile.txt",dictionary.Select(s=>s.ToString());
        

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

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

        【讨论】:

        • 以上内容使以后在 excel 中打开文件变得更容易,如果您使用“myfile.csv”而不是“myfile.txt”,则键和值将分开
        【解决方案7】:
        // Demonstration
        private void WriteDictToFile(Dictionary<string, string> someDict, string path) 
        {
            using (StreamWriter fileWriter = new StreamWriter(path)
            {
                // 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, "PATH\\TO\\FILE");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-21
          • 1970-01-01
          • 2016-08-26
          • 1970-01-01
          • 1970-01-01
          • 2022-01-09
          相关资源
          最近更新 更多