How to write a new line to a txt file in C#?
To write to a txt file and add a new line in C#, you can use the WriteLine method of the StreamWriter class. Here is an example code:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example.txt";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("First line");
writer.WriteLine("Second line");
writer.WriteLine("Third line");
}
Console.WriteLine("Text written to file.");
}
}
In the example above, a StreamWriter object is first created with the specified file path. Then, the WriteLine method is used to write each line of text, automatically adding a newline at the end of each line. Finally, the StreamWriter object is released.