繁体   English   中英

c#如何将字典保存到文本文件

[英]c# how to save dictionary to a text file

我正在尝试将字典保存在 txt 文件中,我正在寻找简单的示例。你能帮我吗? 我正在尝试这个,但它对我不起作用。谢谢。

Dictionary<string, int> set_names = new Dictionary<string, int>();
        //fill dictionary 
        //then do:
        StringBuilder sb =new StringBuilder();
        foreach (KeyValuePair<string, int> kvp in set_names)
        {
            sb.AppendLine(string.Format("{0};{1}", kvp.Key, kvp.Value));
        }

        string filePath = @"C:\myfile.txt";
        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
        {
            using (TextWriter tw = new StreamWriter(fs))

你可以用File.WriteAllLines和一些 Linq 来做到这一点

File.WriteAllLines(
    path, 
    dictionary.Select(kvp => string.Format("{0};{1}", kvp.Key, kvp.Value));

请注意,这将在遍历字典时写入文件,因此不会使用任何额外的内存。

您正在将字典的内容写入sb但从未使用过。 无需先创建字典的内存副本(StringBuilder)。 相反,只需在枚举字典时将其写出来。

string filePath = @"C:\myfile.txt";
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
    using (TextWriter tw = new StreamWriter(fs))

    foreach (KeyValuePair<string, int> kvp in set_names)
    {
        tw.WriteLine(string.Format("{0};{1}", kvp.Key, kvp.Value));
    }
}

用:

StreamWriter sw = new StreamWriter(YOUFILEPATHSTRING);
try
{
 foreach(KeyValuePair kvp in set_names)
 {
   sw.WriteLine(kvp.Key +";"+kvp.Value;
 }

 sw.Close();
}

catch (IOException ex)
{
 sw.Close();
}

这段代码创建了一个指向您正在写入的文件的流,循环遍历键值对并将它们一一写入文件。 如果成功完成或捕获到 IO 异常,则应关闭流,否则该文件可能仍被进程打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM