Movatterモバイル変換


[0]ホーム

URL:


Skip to main contentSkip to in-page navigation

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

StreamWriter Class

Definition

Namespace:
System.IO
Assemblies:
mscorlib.dll, System.IO.dll
Assemblies:
netstandard.dll, System.Runtime.dll
Assembly:
System.IO.dll
Assembly:
System.Runtime.Extensions.dll
Assembly:
mscorlib.dll
Assembly:
netstandard.dll
Source:
StreamWriter.cs
Source:
StreamWriter.cs
Source:
StreamWriter.cs
Source:
StreamWriter.cs

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

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

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

Examples

The following example shows how to use aStreamWriter object to write a file that lists the directories on the C drive, and then uses aStreamReader object to read and display each directory name. A good practice is to use these objects in ausing statement so that the unmanaged resources are correctly disposed. Theusing statement automatically callsDispose 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.IOClass 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 SubEnd Class

Remarks

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

Important

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

StreamWriter defaults to using an instance ofUTF8Encoding unless specified otherwise. This instance ofUTF8Encoding is constructed without a byte order mark (BOM), so itsGetPreamble 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 theEncoding.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 asStreamWriter(String, Boolean, Encoding) orStreamWriter.

By default, aStreamWriter is not thread safe. SeeTextWriter.Synchronized for a thread-safe wrapper.

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

Constructors

NameDescription
StreamWriter(Stream, Encoding, Int32, Boolean)

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

StreamWriter(Stream, Encoding, Int32)

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

StreamWriter(Stream, Encoding)

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

StreamWriter(Stream)

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

StreamWriter(String, Boolean, Encoding, Int32)

Initializes a new instance of theStreamWriter 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.

StreamWriter(String, Boolean, Encoding)

Initializes a new instance of theStreamWriter 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)

Initializes a new instance of theStreamWriter 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, Encoding, FileStreamOptions)

Initializes a new instance of theStreamWriter class for the specified file, using the specified encoding, and configured with the specifiedFileStreamOptions object.

StreamWriter(String, FileStreamOptions)

Initializes a new instance of theStreamWriter class for the specified file, using the default encoding, and configured with the specifiedFileStreamOptions object.

StreamWriter(String)

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

Fields

NameDescription
CoreNewLine

Stores the newline characters used for thisTextWriter.

(Inherited fromTextWriter)
Null

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

Properties

NameDescription
AutoFlush

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

BaseStream

Gets the underlying stream that interfaces with a backing store.

Encoding

Gets theEncoding in which the output is written.

FormatProvider

Gets an object that controls formatting.

(Inherited fromTextWriter)
NewLine

Gets or sets the line terminator string used by the currentTextWriter.

(Inherited fromTextWriter)

Methods

NameDescription
Close()

Closes the currentStreamWriter object and the underlying stream.

CreateObjRef(Type)

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

(Inherited fromMarshalByRefObject)
Dispose()

Releases all resources used by theTextWriter object.

(Inherited fromTextWriter)
Dispose(Boolean)

Causes any buffered data to be written to the underlying stream, releases the unmanaged resources used by theStreamWriter, and optionally the managed resources.

DisposeAsync()

Asynchronously writes any buffered data to the underlying stream and releases the unmanaged resources used by theStreamWriter.

Equals(Object)

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

(Inherited fromObject)
Finalize()

Frees the resources of the currentStreamWriter before it is reclaimed by the garbage collector.

Flush()

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

FlushAsync()

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

FlushAsync(CancellationToken)

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

GetHashCode()

Serves as the default hash function.

(Inherited fromObject)
GetLifetimeService()
Obsolete.

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

(Inherited fromMarshalByRefObject)
GetType()

Gets theType of the current instance.

(Inherited fromObject)
InitializeLifetimeService()
Obsolete.

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

(Inherited fromMarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the currentObject.

(Inherited fromObject)
MemberwiseClone(Boolean)

Creates a shallow copy of the currentMarshalByRefObject object.

(Inherited fromMarshalByRefObject)
ToString()

Returns a string that represents the current object.

(Inherited fromObject)
Write(Boolean)

Writes the text representation of aBoolean value to the text stream.

(Inherited fromTextWriter)
Write(Char)

Writes a character to the stream.

Write(Char[], Int32, Int32)

Writes a subarray of characters to the stream.

Write(Char[])

Writes a character array to the stream.

Write(Decimal)

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

(Inherited fromTextWriter)
Write(Double)

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

(Inherited fromTextWriter)
Write(Int32)

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

(Inherited fromTextWriter)
Write(Int64)

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

(Inherited fromTextWriter)
Write(Object)

Writes the text representation of an object to the text stream by calling theToString method on that object.

(Inherited fromTextWriter)
Write(ReadOnlySpan<Char>)

Writes a character span to the stream.

Write(Single)

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

(Inherited fromTextWriter)
Write(String, Object, Object, Object)

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

Write(String, Object, Object, Object)

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

(Inherited fromTextWriter)
Write(String, Object, Object)

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

Write(String, Object, Object)

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

(Inherited fromTextWriter)
Write(String, Object)

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

Write(String, Object)

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

(Inherited fromTextWriter)
Write(String, Object[])

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

Write(String, Object[])

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

(Inherited fromTextWriter)
Write(String, ReadOnlySpan<Object>)

Writes a formatted string to the stream, using the same semantics asFormat(String, ReadOnlySpan<Object>).

Write(String)

Writes a string to the stream.

Write(StringBuilder)

Writes a string builder to the text stream.

(Inherited fromTextWriter)
Write(UInt32)

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

(Inherited fromTextWriter)
Write(UInt64)

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

(Inherited fromTextWriter)
WriteAsync(Char)

Asynchronously writes a character to the stream.

WriteAsync(Char[], Int32, Int32)

Asynchronously writes a subarray of characters to the stream.

WriteAsync(Char[])

Writes a character array to the text stream asynchronously.

(Inherited fromTextWriter)
WriteAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes a character memory region to the stream.

WriteAsync(String)

Asynchronously writes a string to the stream.

WriteAsync(StringBuilder, CancellationToken)

Asynchronously writes a string builder to the text stream.

(Inherited fromTextWriter)
WriteLine()

Writes a line terminator to the text stream.

(Inherited fromTextWriter)
WriteLine(Boolean)

Writes the text representation of aBoolean value to the text stream, followed by a line terminator.

(Inherited fromTextWriter)
WriteLine(Char)

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

(Inherited fromTextWriter)
WriteLine(Char[], Int32, Int32)

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

(Inherited fromTextWriter)
WriteLine(Char[])

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

(Inherited fromTextWriter)
WriteLine(Decimal)

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

(Inherited fromTextWriter)
WriteLine(Double)

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

(Inherited fromTextWriter)
WriteLine(Int32)

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

(Inherited fromTextWriter)
WriteLine(Int64)

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

(Inherited fromTextWriter)
WriteLine(Object)

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

(Inherited fromTextWriter)
WriteLine(ReadOnlySpan<Char>)

Writes the text representation of a character span to the stream, followed by a line terminator.

WriteLine(Single)

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

(Inherited fromTextWriter)
WriteLine(String, Object, Object, Object)

Writes out a formatted string and a new line to the stream, using the same semantics asFormat(String, Object).

WriteLine(String, Object, Object, Object)

Writes out a formatted string and a new line to the text stream, using the same semantics asFormat(String, Object).

(Inherited fromTextWriter)
WriteLine(String, Object, Object)

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

WriteLine(String, Object, Object)

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

(Inherited fromTextWriter)
WriteLine(String, Object)

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

WriteLine(String, Object)

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

(Inherited fromTextWriter)
WriteLine(String, Object[])

Writes out a formatted string and a new line to the stream, using the same semantics asFormat(String, Object).

WriteLine(String, Object[])

Writes out a formatted string and a new line to the text stream, using the same semantics asFormat(String, Object).

(Inherited fromTextWriter)
WriteLine(String, ReadOnlySpan<Object>)

Writes out a formatted string and a new line to the stream, using the same semantics asFormat(String, ReadOnlySpan<Object>).

WriteLine(String)

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

WriteLine(String)

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

(Inherited fromTextWriter)
WriteLine(StringBuilder)

Writes the text representation of a string builder to the text stream, followed by a line terminator.

(Inherited fromTextWriter)
WriteLine(UInt32)

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

(Inherited fromTextWriter)
WriteLine(UInt64)

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

(Inherited fromTextWriter)
WriteLineAsync()

Asynchronously writes a line terminator to the stream.

WriteLineAsync(Char)

Asynchronously writes a character to the stream, followed by a line terminator.

WriteLineAsync(Char[], Int32, Int32)

Asynchronously writes a subarray of characters to the stream, followed by a line terminator.

WriteLineAsync(Char[])

Asynchronously writes an array of characters to the text stream, followed by a line terminator.

(Inherited fromTextWriter)
WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes the text representation of a character memory region to the stream, followed by a line terminator.

WriteLineAsync(String)

Asynchronously writes a string to the stream, followed by a line terminator.

WriteLineAsync(StringBuilder, CancellationToken)

Asynchronously writes the text representation of a string builder to the text stream, followed by a line terminator.

(Inherited fromTextWriter)

Explicit Interface Implementations

NameDescription
IDisposable.Dispose()

For a description of this member, seeDispose().

(Inherited fromTextWriter)

Extension Methods

NameDescription
ConfigureAwait(IAsyncDisposable, Boolean)

Configures how awaits on the tasks returned from an async disposable will be performed.

Applies to

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?