I have a dictionary object of type Dictionary
and trying to use StreamWriter to output the entire content to a text file but failed to find the correct method from the Dictionary class.
using (StreamWriter sw = new StreamWriter("myfile.txt")) { sw.WriteLine(dictionary.First()); }
I can only retrieve the first element and it is bounded by a square bracket plus a comma separator in between as well:
[Peter, Admin]
and would be nice to have [Peter Admin] (without the comma)
Write dictionary to file using For loop The simple method to write a dictionary to a text file is by using the 'for' loop. First Open the file in write mode by using the File open() method. Then Get the key and value pair using the dictionary items() method from the Dictionary.
File.WriteAllLines("myfile.txt", dictionary.Select(x => "[" + x.Key + " " + x.Value + "]").ToArray());
(And if you're using .NET4 then you can omit the final ToArray
call.)
You need to loop over the entries yourself:
using (StreamWriter file = new StreamWriter("myfile.txt")) foreach (var entry in dictionary) file.WriteLine("[{0} {1}]", entry.Key, entry.Value);
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