Diana Nikolova
Diana Nikolova

Reputation: 31

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

Upvotes: 3

Views: 7260

Answers (3)

Omar Zaarour
Omar Zaarour

Reputation: 302

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.

Upvotes: 0

juharr
juharr

Reputation: 32266

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.

Upvotes: 3

Eric J.
Eric J.

Reputation: 150108

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

Upvotes: 3

Related Questions