Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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))
like image 332
Diana Nikolova Avatar asked Nov 19 '25 05:11

Diana Nikolova


2 Answers

You are writing the contents of your dictionary into sb but never using it. There is no need to first create an in-memory copy of your dictionary (the 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));
    }
}
like image 181
Eric J. Avatar answered Nov 21 '25 20:11

Eric J.


You can do this with File.WriteAllLines and some 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.

like image 25
juharr Avatar answered Nov 21 '25 19:11

juharr