Stream​Writer Class

Definition

Implements a TextWriter for writing characters to a stream in a particular encoding.

[System.Runtime.InteropServices.ComVisible(true)]
public class StreamWriter : System.IO.TextWriter
Inheritance
Attributes

Inherited Members

System.IO.TextWriter

System.MarshalByRefObject

System.Object

Examples

The following example shows how to use a StreamWriter object to write a file that lists the directories on the C drive, and then uses a StreamReader object to read and display each directory name. A good practice is to use these objects in a using statement so that the unmanaged resources are correctly disposed. The using statement automatically calls Dispose on the object when the code that is using it has completed. The constructor used in this example is not supported for use in Windows Store Apps.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace StreamReadWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the directories currently on the C drive.
            DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();

            // Write each directory name to a file.
            using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
            {
                foreach (DirectoryInfo dir in cDirs)
                {
                    sw.WriteLine(dir.Name);

                }
            }

            // Read and show each line from the file.
            string line = "";
            using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}
Imports System.IO
Class Program

    Shared Sub Main()

        ' Get the directories currently on the C drive.
        Dim cDirs As DirectoryInfo() = New DirectoryInfo("c:\").GetDirectories()

        ' Write each directory name to a file.
        Using sw As StreamWriter = New StreamWriter("CDriveDirs.txt")
            For Each Dir As DirectoryInfo In cDirs
                sw.WriteLine(Dir.Name)
            Next
        End Using

        'Read and show each line from the file.
        Dim line As String = ""
        Using sr As StreamReader = New StreamReader("CDriveDirs.txt")
            Do
                line = sr.ReadLine()
                Console.WriteLine(line)
            Loop Until line Is Nothing
        End Using


    End Sub

End Class

Remarks

Note

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

StreamWriter is designed for character output in a particular encoding, whereas classes derived from Stream are designed for byte input and output.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM), so its GetPreamble method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the System.Text.Encoding.UTF8 property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter(String, Boolean, Encoding) or StreamWriter.

By default, a StreamWriter is not thread safe. See System.IO.TextWriter.Synchronized for a thread-safe wrapper.

For a list of common I/O tasks, see Common I/O Tasks.

Constructors

Stream​Writer(​Stream)

Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.

Stream​Writer(​String)

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size.

Stream​Writer(​Stream, ​Encoding)

Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and the default buffer size.

Stream​Writer(​String, ​Boolean)

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Stream​Writer(​Stream, ​Encoding, ​Int32)

Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size.

Stream​Writer(​String, ​Boolean, ​Encoding)

Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Stream​Writer(​Stream, ​Encoding, ​Int32, ​Boolean)

Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.

Stream​Writer(​String, ​Boolean, ​Encoding, ​Int32)

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the specified encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Fields

Null

Provides a StreamWriter with no backing store that can be written to, but not read from.

Properties

Auto​Flush

Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to Write(Char).

Base​Stream

Gets the underlying stream that interfaces with a backing store.

Encoding

Gets the Encoding in which the output is written.

Methods

Close()

Closes the current StreamWriter object and the underlying stream.

Dispose(​Boolean)

Releases the unmanaged resources used by the StreamWriter and optionally releases the managed resources.

Flush()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Flush​Async()

Clears all buffers for this stream asynchronously and causes any buffered data to be written to the underlying device.

Write(​Char)

Writes a character to the stream.

Write(​Char[])

Writes a character array to the stream.

Write(​String)

Writes a string to the stream.

Write(​Char[], ​Int32, ​Int32)

Writes a subarray of characters to the stream.

Write​Async(​Char)

Writes a character to the stream asynchronously.

Write​Async(​String)

Writes a string to the stream asynchronously.

Write​Async(​Char[], ​Int32, ​Int32)

Writes a subarray of characters to the stream asynchronously.

Write​Line​Async()

Writes a line terminator asynchronously to the stream.

Write​Line​Async(​Char)

Writes a character followed by a line terminator asynchronously to the stream.

Write​Line​Async(​String)

Writes a string followed by a line terminator asynchronously to the stream.

Write​Line​Async(​Char[], ​Int32, ​Int32)

Writes a subarray of characters followed by a line terminator asynchronously to the stream.