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))
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));
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With