Continuing with my new C# “how-to” theme, the code snippet below shows how to create a text file and write content to it using the StreamWriter class. Remember to add the “using System.IO;” directive at the top. Note that there is a StreamWriter constructor which supports a Boolean parameter “append” – if you pass true for this parameter and the file already exists, the StreamWriter will append content to the file rather than overwrite the existing content.

const string TextFilePath = @“C:\WriteTest.txt”;

using (StreamWriter writer = new StreamWriter(TextFilePath))
{
writer.WriteLine(“Hello, world”);
writer.WriteLine(“Bye, world”);
}