Write to a text file in C#

We can StreamWriter class to write to a file. The Write method is used to write to a text file.

In the StreamWriter constructor, the first parameter is the file name and second parameter is optional, boolean type. If second parameter is true, an existing file will be appended with new text. Otherwise it will erase old text and start with new text.
 

try

{

    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName, true))

    {

        writer.Write("Write some text here");

    }

}

catch (Exception exp)

{

    Console.WriteLine(exp.Message);

}