StreamWriter in C#


Write characters to a stream with StreamWriter in C#.

With StreamWriter, create a new file −

StreamWriter sw = new StreamWriter("hello.txt"))

Add text to the file −

sw.WriteLine("Hello");
sw.WriteLine("World");

The following is the code −

Example

using System.IO;

public class Program {
   public static void Main() {
      using (StreamWriter sw = new StreamWriter("hello.txt")) {
         sw.WriteLine("Hello");
         sw.WriteLine("World");
      }
   }
}

It creates the file “hello.text” and adds text to it −

Output

The following is the output.

Hello
World

Updated on: 03-Apr-2020

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements