Export (0) Print
Expand All

StreamWriter Class

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

For a list of all members of this type, see StreamWriter Members.

System.Object
   System.MarshalByRefObject
      System.IO.TextWriter
         System.IO.StreamWriter

[Visual Basic]
<Serializable>
Public Class StreamWriter
   Inherits TextWriter
[C#]
[Serializable]
public class StreamWriter : TextWriter
[C++]
[Serializable]
public __gc class StreamWriter : public TextWriter
[JScript]
public
   Serializable
class StreamWriter extends TextWriter

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

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

StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed such that the Encoding.GetPreamble method returns the Unicode byte order mark written in UTF-8. The preamble of the encoding is added to a stream when you are not appending to an existing stream. This means any text file you create with StreamWriter will have three byte order marks at its beginning. UTF-8 handles all Unicode characters correctly and gives consistent results on localized versions of the operating system.

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

The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File

Requirements

Namespace: System.IO

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

StreamWriter Members | System.IO Namespace | Stream | StreamReader | Encoder | Encoding | Working with I/O | Reading Text from a File | Writing Text to a File | Basic File I/O | Reading and Writing to a Newly Created Data File

Show:
© 2014 Microsoft