简体   繁体   English

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

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

I am trying to save dictionary in txt file and I am looking for simple examples.Can you help me,please?我正在尝试将字典保存在 txt 文件中,我正在寻找简单的示例。你能帮我吗? I am trying this but it does not work for me.Thanks.我正在尝试这个,但它对我不起作用。谢谢。

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

You can do this with File.WriteAllLines and some Linq你可以用File.WriteAllLines和一些 Linq 来做到这一点

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

Note that this will write to the file as it loops through the dictionary thus not using any additional memory.请注意,这将在遍历字典时写入文件,因此不会使用任何额外的内存。

You are writing the contents of your dictionary into sb but never using it.您正在将字典的内容写入sb但从未使用过。 There is no need to first create an in-memory copy of your dictionary (the StringBuilder).无需先创建字典的内存副本(StringBuilder)。 Instead, just write it out as you enumerate the dictionary.相反,只需在枚举字典时将其写出来。

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

Use:用:

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

This code create a stream pointed to the file you are writing to, loops over the Key value pairs and write them one by one to the file.这段代码创建了一个指向您正在写入的文件的流,循环遍历键值对并将它们一一写入文件。 The stream should be closed in the event of successful completion or if an IO exception is caught, otherwise the file may still opened by the process.如果成功完成或捕获到 IO 异常,则应关闭流,否则该文件可能仍被进程打开。

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

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