Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the content of a dictionary to a text file?

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)

like image 491
Chris Avatar asked Jun 18 '10 04:06

Chris


People also ask

How do you write a dictionary in a text file?

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.


2 Answers

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

like image 140
LukeH Avatar answered Sep 21 '22 04:09

LukeH


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);  
like image 42
porges Avatar answered Sep 24 '22 04:09

porges