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

foreach (KeyValuePair<string,string>  kvp in dictionary)
{
     System.IO.File.AppendAllText("dictionary.txt", string.Format("{0} {1} {2}", kvp.Key,    kvp.Value, Environment.NewLine));
}

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


// Demonstration
private void WriteDictToFile(Dictionary<string, string> someDict, string path) 
{
    using (StreamWriter fileWriter = new StreamWriter(path)
    {
        // You can modify <string, string> notation by placing your types.
        foreach (KeyValuePair<string, string> kvPair in someDict) 
        {
            fileWriter.WriteLine("{0}: {1}", kvPair.Key, kvPair.Value);
        }
        fileWriter.Close();
    }
}

And to use in Main

static void Main(string[] args) 
{
    Dictionary<string, string> dataDict = new Dictionary<string, string>();
    Console.Write("Enter your name: ");
    string n = Console.ReadLine();
    Console.Write("Enter your surname: ");
    string s = Console.ReadLine();
    dataDict.Add("Name", n)
    dataDict.Add("Surname", s)
    WriteDictToFile(dataDict, "PATH\\TO\\FILE");
}

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