C# TextWriter

In c#, TextWriter is a class of System.IO namespace and it is useful to write a text or sequential series of characters in the file. The TextWriter is an abstract class and it writes the characters to streams and strings.

 

Now, we will see how to use TextWriter class in c# to write a text or sequential series of characters in the file with examples.

C# TextWriter Example

Following is the example of writing a text or sequential series of characters in a file using the TextWriter 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

            using (TextWriter wr = File.CreateText(fpath))

            {

                wr.WriteLine("Hi");

                wr.WriteLine("\r\nWelcome to Tutlane");

                wr.WriteLine("\r\nTextWriter Example");

            }

        }

    }

}

If you observe the above example, we imported a System.IO namespace in our example to access File & TextWriter 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 below.

 

C# TextWriter to Write a Text to File Example Result

 

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

 

PREVIOUS

C# FileStream
 

NEXT

C# TextReader  
 

Topics Covered