Introduction
StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter.Write() method is responsible for writing text to a stream. StreamWriter class is inherited from the TextWriter class that provides methods to write an object to a string, write strings to a file, or to serialize XML.
StreamWriter is defined in the System.IO namespace. StreamWriter provides the following Write methods.
- Write: Write data to the stream.
- WriteAsync: Writes data to the stream asynchronously.
- WriteLine: Writes a line terminator to the text string or stream.
- WriteLineAsync: Writes a line terminator to the text string or stream asynchronously.
Creating a StreamWriter using a Filename
StreamWriter constructor takes a file name or a FileStream object with Encoding and buffer size as optional parameters.

The following code snippet creates a StreamWriter from a filename with default encoding and buffer size.
// File name
string fileName = @"C:\Temp\Mahesh.txt";
StreamWriter writer = new StreamWriter(fileName);
The following code snippet creates a StreamWriter and adds some text to the writer using StreamWriter.Write method. If the file does not exist, the writer will create a new file. If the file already exists, the writer will override its content.
string fileName = @"C:\Temp\CSharpAuthors.txt";
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write("This file contains C# Corner Authors.");
}
}
catch(Exception exp)
{
Console.Write(exp.Message);
}
Creating a StreamWriter using a FileStream
StreamWriter constructor takes a FileStream object with Encoding and buffer size as optional parameters. The following code snippet creates a StreamWriter from a FileStream with default encoding and buffer size.
// Create a FileStream with mode CreateNew
FileStream stream = new FileStream(fileName, FileMode.CreateNew);
// Create a StreamWriter from FileStream
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("Hello StreamWriter");
}
The following code snippet creates a StreamWriter from a FileStream with Encoding. Encoding supported are ASCII, Unicode, UTF32, UTF7, and UTF8. Encoding is defined in the System.Text namespace.
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF32))
The following code snippet creates a StreamWriter from a FileStream with encoding and buffer size.
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF32, 512))
StreamWriter.Write() method
StreamWriter.Write() method writes a char, string of chars, or a string to the steam. The following code snippet creates and writes different content to the stream.
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))
{
// Write a char
writer.Write('y');
// Write a char[]
char[] arr = { '1', '3', '5', '7' };
writer.Write(arr);
string author = "Mahesh Chand";
// Write a string
writer.Write(author);
} 

David MccarterPosted Jun 10, 2019, 5:56 PM
Why didn't you use using for FileStream?