How To Create Text File And Write To It

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. 
  1. conststring TextFilePath = @“C:\WriteTest.txt”;  
  2. using (StreamWriter writer = new StreamWriter(TextFilePath))  
  3. {  
  4.    writer.WriteLine(“Hello, world”);  
  5.    writer.WriteLine(“Bye, world”);  
  6. }  
StreamWriter class provides several other methods to write to files. 
 
Here is a detailed tutorial: StreamWriter In C#