StreamWriter StreamWriter StreamWriter StreamWriter Class

Definition

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

public ref class StreamWriter : System::IO::TextWriter
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class StreamWriter : System.IO.TextWriter
type StreamWriter = class
    inherit TextWriter
Public Class StreamWriter
Inherits TextWriter
Inheritance
Attributes
ComVisibleAttribute SerializableAttribute

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

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 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 TextWriter.Synchronized for a thread-safe wrapper.

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

Constructors

StreamWriter(Stream) StreamWriter(Stream) StreamWriter(Stream) StreamWriter(Stream)

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

StreamWriter(Stream, Encoding) StreamWriter(Stream, Encoding) StreamWriter(Stream, Encoding) StreamWriter(Stream, Encoding)

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

StreamWriter(Stream, Encoding, Int32) StreamWriter(Stream, Encoding, Int32) StreamWriter(Stream, Encoding, Int32) StreamWriter(Stream, Encoding, Int32)

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

StreamWriter(Stream, Encoding, Int32, Boolean) StreamWriter(Stream, Encoding, Int32, Boolean) StreamWriter(Stream, Encoding, Int32, Boolean) StreamWriter(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.

StreamWriter(String) StreamWriter(String) StreamWriter(String) StreamWriter(String)

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

StreamWriter(String, Boolean) StreamWriter(String, Boolean) StreamWriter(String, Boolean) StreamWriter(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.

StreamWriter(String, Boolean, Encoding) StreamWriter(String, Boolean, Encoding) StreamWriter(String, Boolean, Encoding) StreamWriter(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.

StreamWriter(String, Boolean, Encoding, Int32) StreamWriter(String, Boolean, Encoding, Int32) StreamWriter(String, Boolean, Encoding, Int32) StreamWriter(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

CoreNewLine CoreNewLine CoreNewLine CoreNewLine

Stores the newline characters used for this TextWriter.

(Inherited from TextWriter)
Null Null Null Null

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

Properties

AutoFlush AutoFlush AutoFlush AutoFlush

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

BaseStream BaseStream BaseStream BaseStream

Gets the underlying stream that interfaces with a backing store.

Encoding Encoding Encoding Encoding

Gets the Encoding in which the output is written.

FormatProvider FormatProvider FormatProvider FormatProvider

Gets an object that controls formatting.

(Inherited from TextWriter)
NewLine NewLine NewLine NewLine

Gets or sets the line terminator string used by the current TextWriter.

(Inherited from TextWriter)

Methods

Close() Close() Close() Close()

Closes the current StreamWriter object and the underlying stream.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Releases all resources used by the TextWriter object.

(Inherited from TextWriter)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()
Flush() Flush() Flush() Flush()

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

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)
Write(Boolean) Write(Boolean) Write(Boolean) Write(Boolean)

Writes the text representation of a Boolean value to the text string or stream.

(Inherited from TextWriter)
Write(Char) Write(Char) Write(Char) Write(Char)

Writes a character to the stream.

Write(Char[]) Write(Char[]) Write(Char[]) Write(Char[])

Writes a character array to the stream.

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

Writes a subarray of characters to the stream.

Write(Decimal) Write(Decimal) Write(Decimal) Write(Decimal)

Writes the text representation of a decimal value to the text string or stream.

(Inherited from TextWriter)
Write(Double) Write(Double) Write(Double) Write(Double)

Writes the text representation of an 8-byte floating-point value to the text string or stream.

(Inherited from TextWriter)
Write(Int32) Write(Int32) Write(Int32) Write(Int32)

Writes the text representation of a 4-byte signed integer to the text string or stream.

(Inherited from TextWriter)
Write(Int64) Write(Int64) Write(Int64) Write(Int64)

Writes the text representation of an 8-byte signed integer to the text string or stream.

(Inherited from TextWriter)
Write(Object) Write(Object) Write(Object) Write(Object)

Writes the text representation of an object to the text string or stream by calling the ToString method on that object.

(Inherited from TextWriter)
Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>)
Write(Single) Write(Single) Write(Single) Write(Single)

Writes the text representation of a 4-byte floating-point value to the text string or stream.

(Inherited from TextWriter)
Write(String) Write(String) Write(String) Write(String)

Writes a string to the stream.

Write(String, Object) Write(String, Object) Write(String, Object) Write(String, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object) method.

(Inherited from TextWriter)
Write(String, Object, Object) Write(String, Object, Object) Write(String, Object, Object) Write(String, Object, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object, Object) method.

(Inherited from TextWriter)
Write(String, Object, Object, Object) Write(String, Object, Object, Object) Write(String, Object, Object, Object) Write(String, Object, Object, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object, Object, Object) method.

(Inherited from TextWriter)
Write(String, Object[]) Write(String, Object[]) Write(String, Object[]) Write(String, Object[])

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object[]) method.

(Inherited from TextWriter)
Write(UInt32) Write(UInt32) Write(UInt32) Write(UInt32)

Writes the text representation of a 4-byte unsigned integer to the text string or stream.

(Inherited from TextWriter)
Write(UInt64) Write(UInt64) Write(UInt64) Write(UInt64)

Writes the text representation of an 8-byte unsigned integer to the text string or stream.

(Inherited from TextWriter)
WriteAsync(Char) WriteAsync(Char) WriteAsync(Char) WriteAsync(Char)

Writes a character to the stream asynchronously.

WriteAsync(Char[]) WriteAsync(Char[]) WriteAsync(Char[]) WriteAsync(Char[])

Writes a character array to the text string or stream asynchronously.

(Inherited from TextWriter)
WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32)

Writes a subarray of characters to the stream asynchronously.

WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken)
WriteAsync(String) WriteAsync(String) WriteAsync(String) WriteAsync(String)

Writes a string to the stream asynchronously.

WriteLine() WriteLine() WriteLine() WriteLine()

Writes a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean)

Writes the text representation of a Boolean value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char) WriteLine(Char) WriteLine(Char) WriteLine(Char)

Writes a character followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char[]) WriteLine(Char[]) WriteLine(Char[]) WriteLine(Char[])

Writes an array of characters followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32)

Writes a subarray of characters followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Decimal) WriteLine(Decimal) WriteLine(Decimal) WriteLine(Decimal)

Writes the text representation of a decimal value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Double) WriteLine(Double) WriteLine(Double) WriteLine(Double)

Writes the text representation of a 8-byte floating-point value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Int32) WriteLine(Int32) WriteLine(Int32) WriteLine(Int32)

Writes the text representation of a 4-byte signed integer followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Int64) WriteLine(Int64) WriteLine(Int64) WriteLine(Int64)

Writes the text representation of an 8-byte signed integer followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Object) WriteLine(Object) WriteLine(Object) WriteLine(Object)

Writes the text representation of an object by calling the ToString method on that object, followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>)
WriteLine(Single) WriteLine(Single) WriteLine(Single) WriteLine(Single)

Writes the text representation of a 4-byte floating-point value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(String) WriteLine(String) WriteLine(String) WriteLine(String)
WriteLine(String, Object) WriteLine(String, Object) WriteLine(String, Object) WriteLine(String, Object)

Writes a formatted string and a new line to the text string or stream, using the same semantics as the Format(String, Object) method.

(Inherited from TextWriter)
WriteLine(String, Object, Object) WriteLine(String, Object, Object) WriteLine(String, Object, Object) WriteLine(String, Object, Object)

Writes a formatted string and a new line to the text string or stream, using the same semantics as the Format(String, Object, Object) method.

(Inherited from TextWriter)
WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object)

Writes out a formatted string and a new line, using the same semantics as Format(String, Object).

(Inherited from TextWriter)
WriteLine(String, Object[]) WriteLine(String, Object[]) WriteLine(String, Object[]) WriteLine(String, Object[])

Writes out a formatted string and a new line, using the same semantics as Format(String, Object).

(Inherited from TextWriter)
WriteLine(UInt32) WriteLine(UInt32) WriteLine(UInt32) WriteLine(UInt32)

Writes the text representation of a 4-byte unsigned integer followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(UInt64) WriteLine(UInt64) WriteLine(UInt64) WriteLine(UInt64)

Writes the text representation of an 8-byte unsigned integer followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLineAsync() WriteLineAsync() WriteLineAsync() WriteLineAsync()

Writes a line terminator asynchronously to the stream.

WriteLineAsync(Char) WriteLineAsync(Char) WriteLineAsync(Char) WriteLineAsync(Char)

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

WriteLineAsync(Char[]) WriteLineAsync(Char[]) WriteLineAsync(Char[]) WriteLineAsync(Char[])

Writes an array of characters followed by a line terminator asynchronously to the text string or stream.

(Inherited from TextWriter)
WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32)

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

WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken)
WriteLineAsync(String) WriteLineAsync(String) WriteLineAsync(String) WriteLineAsync(String)

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

Explicit Interface Implementations

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() Inherited from TextWriter

Applies to

See Also