views:

88

answers:

5

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)

+2  A: 

You need to loop over the entries yourself:

using (var file = File.OpenWrite("myfile.txt"))
    foreach (var entry in dictionary)
        file.WriteLine("[{0} {1}]", entry.Key, entry.Value); 
Porges
Thanks, my colleague has pointed out I can do something like...foreach(KeyValuePair<string, string> entry in dictionary) sw.WriteLine(entry.Key + entry.Value);
codemonkie
A: 

You need to select the strings you wish to write, and iterate over the resulting enumeration to write each line:

var dataToWrite = from kvp in dictionary
                  select String.Format("[{0} {1}"], kvp.Key kvp.Value);

using (StreamWriter sw = new StreamWriter("myfile.txt"))
{
    foreach (string dataLine in dataToWrite)
    {
        sw.WriteLine(dataLine);
    }
}
jrista
A: 
foreach (KeyValuePair<string,string>  kvp in dictionary)
{
     System.IO.File.AppendAllText("dictionary.txt", string.Format("{0} {1} {2}", kvp.Key,    kvp.Value, Environment.NewLine));
}
cptScarlet
A: 
var pairs = from p in yourDictionary.Keys
    select new {Key=p, Value=yourDictionary[p]};

foreach(var pair in pairs)
    yourStreamWriter.WriteLine("Key={0}, Value={1}", pair.Key, pair.Value);
deostroll
A: 
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.)

LukeH