C# StreamWriter

In c#, StreamWriter is a class of System.IO namespace, and it is useful to write characters to the stream with a particular encoding. The StreamWriter class has been derived from TextWriter to provide the implementation of members for writing to a stream, and by default, it will use UTF8Encoding unless we specify other encodings.

 

Now, we will see how to use the StreamWriter class in c# to write a text to the file with examples.

C# StreamWriter Example

Following is the example of writing a text to file using the StreamWriter object in c#.

 

using System.IO;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          string fpath = @"D:\Test.txt";
          // Check file if exists
          if (File.Exists(fpath))
          {
             File.Delete(fpath);
          }
          // Create the file
          FileStream fs = new FileStream(fpath, FileMode.Create);
          using (StreamWriter sw = new StreamWriter(fs))
          {
             sw.WriteLine("Hi");
             sw.WriteLine("\r\nWelcome to Tutlane");
             sw.WriteLine("\r\nStreamWriter Example");
          }
       }
    }
}

If you observe the above example, we imported a System.IO namespace to access File, FileStream & StreamWriter objects to delete, create and write a text to file.

 

When we execute the above example, it will create a new “Test.txt” file in D drive with required text like as shown following.

 

C# StreamWriter Example Result

 

This is how we can create, delete and add text to files using File, FileStream & StreamWriter objects in c#.