Home
Map
TextWriter ExampleUse the TextWriter class. TextWriter is returned by File.CreateText.
C#
This page was last reviewed on Nov 15, 2023.
TextWriter creates text output. This C# class is used to implement other file classes in the base class library. You can also use it to implement file IO logic.
TextReader
Used by StreamWriter. TextWriter is used to implement StreamWriter. It lacks helpful features, but is still useful when we want to use a specific text encoding.
StreamWriter
Example. First here we look at the TextWriter class, which we instantiate from the result of the File.CreateText static method in the System.IO namespace.
File
Start The TextWriter class is easiest to use reliably when you wrap it in a using statement and a resource acquisition statement.
using
Info The program uses the WriteLine method and the Write method on the TextWriter instance we allocated.
Note The Write() method does not add the newline sequence. It just writes the character data specified.
Note 2 The program uses the NewLine property. By default, it will be set to the platform's default newline sequence.
Environment.NewLine
using System.IO; class Program { static void Main() { // // Create a new TextWriter in the resource acquisition statement. // using (TextWriter writer = File.CreateText("C:\\perl.txt")) { // // Write one line. // writer.WriteLine("First line"); // // Write two strings. // writer.Write("A "); writer.Write("B "); // // Write the default newline. // writer.Write(writer.NewLine); } } }
First line A B
StreamWriter. The StreamWriter class inherits from TextWriter. The TextWriter class is an abstract base class, which means it provides functionality for StreamWriter.
Note Microsoft states that StreamWriter represents writing in a particular encoding.
And For this reason, unless you have specialized encoding requirements, StreamWriter is more appropriate because it manages the encoding.
Summary. We looked at the TextWriter class and related it to the StreamWriter class by noting that it is used as a base class. TextWriter does not handle encodings automatically.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 15, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.