Visual C# Guide
Writing Text Files

Writing to a text file is a very similar process to reading. The main difference is that sometimes we will want to overwrite the contents of a file, sometimes we will want to append information to it.

Append All Text/Write All Text

string path = @"C:\q.txt";
string textToEnter = "What is the capital of Spain?";
File.AppendAllText(path, textToEnter);
Console.WriteLine("Appended Text To File");

If the file specified in the first line does not exist, it will be created. The alternative to this is to use the WriteAllText() method.

Writing A Line At A Time

In the same way that we can use a streamreader to read the file, we can use a streamwriter to write one.

string path = @"C:\q.txt"; StreamWriter sw = new StreamWriter(path);
Console.Write("Enter some text to add to the file: ");
string textInput = Console.ReadLine();
while (textInput != "end")
   Console.Write("Enter some text to add to the file: ");
   textInput = Console.ReadLine();
Console.WriteLine("Finished writing to the file");

There are quite a few additional techniques that you might use for writing to text files. The MSDN for C# has fairly good explanations and examples on the topic.