StreamWriter 類別

定義

實作以特定的編碼方式將字元寫入位元組資料流的 TextWriterImplements a TextWriter for writing characters to a stream in a particular encoding.

public ref class StreamWriter : System::IO::TextWriter
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class StreamWriter : System.IO.TextWriter
type StreamWriter = class
    inherit TextWriter
Public Class StreamWriter
Inherits TextWriter
繼承
屬性

範例

下列範例示範如何使用StreamWriter物件寫入檔案,該檔案會列出 C 磁片磁碟機上的目錄,然後StreamReader使用物件來讀取和顯示每個目錄名稱。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. 理想的作法是在using語句中使用這些物件,以便正確處置非受控資源。A good practice is to use these objects in a using statement so that the unmanaged resources are correctly disposed. 語句會在使用它的程式碼完成時,自動在物件上呼叫DisposeusingThe using statement automatically calls Dispose on the object when the code that is using it has completed. 在此範例中使用的函式不支援在應用Windows 市集Windows Store程式中使用。The constructor used in this example is not supported for use in Windows 市集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

備註

StreamWriter是針對特定編碼中的字元輸出所設計,而衍生自Stream的類別則是針對位元組輸入和輸出而設計。StreamWriter is designed for character output in a particular encoding, whereas classes derived from Stream are designed for byte input and output.

重要

此型別代表 IDisposable 介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

StreamWriterUTF8Encoding除非另有指定,否則預設為使用的實例。StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. 這個實例的UTF8Encoding結構不含位元組順序標記(BOM),因此其GetPreamble方法會傳回空的位元組陣列。This instance of UTF8Encoding is constructed without a byte order mark (BOM), so its GetPreamble method returns an empty byte array. 此函式的預設 UTF-8 編碼會在不正確位元組上擲回例外狀況。The default UTF-8 encoding for this constructor throws an exception on invalid bytes. 此行為不同于Encoding.UTF8屬性中的編碼物件所提供的行為。This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. 若要指定 BOM 並判斷是否在不正確位元組上擲回例外狀況,請使用接受編碼物件做為參數的函式, StreamWriter(String, Boolean, Encoding)例如StreamWriter或。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.

根據預設, StreamWriter不是安全線程。By default, a StreamWriter is not thread safe. TextWriter.Synchronized需安全線程的包裝函式,請參閱。See TextWriter.Synchronized for a thread-safe wrapper.

如需一般 i/o 工作的清單, 請參閱一般 i/o工作。For a list of common I/O tasks, see Common I/O Tasks.

建構函式

StreamWriter(Stream)

使用 UTF-8 編碼方式和預設緩衝區大小,為指定的資料流初始化 StreamWriter 類別的新執行個體。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 類別的新執行個體。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 類別的新執行個體。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 類別的新執行個體,並選擇性讓資料流保持開啟。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 類別的新執行個體。Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size.

StreamWriter(String, Boolean)

使用預設編碼方式和緩衝區大小,為指定的檔案初始化 StreamWriter 類別的新執行個體。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 類別的新執行個體。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 類別的新執行個體。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.

欄位

CoreNewLine

儲存這個 TextWriter 所使用的新行字元。Stores the newline characters used for this TextWriter.

(繼承來源 TextWriter)
Null

提供 StreamWriter,但不包含可寫入但無法讀取的備份存放區。Provides a StreamWriter with no backing store that can be written to, but not read from.

屬性

AutoFlush

取得或設定值,指出 StreamWriter 在每次呼叫 Write(Char) 之後,是否要將其緩衝區清除到基礎資料流。Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to Write(Char).

BaseStream

取得以備份存放區作介面的基礎資料流。Gets the underlying stream that interfaces with a backing store.

Encoding

取得寫入輸出的 EncodingGets the Encoding in which the output is written.

FormatProvider

取得控制格式設定的物件。Gets an object that controls formatting.

(繼承來源 TextWriter)
NewLine

取得或設定目前 TextWriter 所使用的行結束字元字串。Gets or sets the line terminator string used by the current TextWriter.

(繼承來源 TextWriter)

方法

Close()

關閉目前的 StreamWriter 物件和基礎資料流。Closes the current StreamWriter object and the underlying stream.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
Dispose()

釋放由 TextWriter 物件使用的所有資源。Releases all resources used by the TextWriter object.

(繼承來源 TextWriter)
Dispose(Boolean)

使任何緩衝資料都寫入基礎資料流,釋放 StreamWriter 所使用的非受控資源,然後選擇性地釋放受控資源。Causes any buffered data to be written to the underlying stream, releases the unmanaged resources used by the StreamWriter, and optionally the managed resources.

DisposeAsync()

以非同步方式將任何緩衝資料寫入基礎資料流,並釋出 StreamWriter 使用的非受控資源。Asynchronously writes any buffered data to the underlying stream and releases the unmanaged resources used by the StreamWriter.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

在記憶體回收行程回收目前 StreamWriter 的資源前,先將它的資源釋放。Frees the resources of the current StreamWriter before it is reclaimed by the garbage collector.

Flush()

清除目前寫入器 (Writer) 的所有緩衝區,並且造成任何緩衝資料都寫入基礎資料流。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.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Write(Boolean)

Boolean 值的文字表示寫入文字資料流。Writes the text representation of a Boolean value to the text stream.

(繼承來源 TextWriter)
Write(Char)

將一個字元寫入資料流。Writes a character to the stream.

Write(Char[])

將字元陣列寫入資料流。Writes a character array to the stream.

Write(Char[], Int32, Int32)

將字元子陣列寫入資料流。Writes a subarray of characters to the stream.

Write(Decimal)

將十進位值的文字表示寫入文字資料流。Writes the text representation of a decimal value to the text stream.

(繼承來源 TextWriter)
Write(Double)

將 8 位元組浮點數值的文字表示寫入文字資料流。Writes the text representation of an 8-byte floating-point value to the text stream.

(繼承來源 TextWriter)
Write(Int32)

將 4 位元組帶正負號的整數文字表示寫入文字資料流。Writes the text representation of a 4-byte signed integer to the text stream.

(繼承來源 TextWriter)
Write(Int64)

將 8 位元組帶正負號的整數文字表示寫入文字資料流。Writes the text representation of an 8-byte signed integer to the text stream.

(繼承來源 TextWriter)
Write(Object)

呼叫該物件的 ToString 方法,將物件的文字表示寫入文字資料流。Writes the text representation of an object to the text stream by calling the ToString method on that object.

(繼承來源 TextWriter)
Write(ReadOnlySpan<Char>)

將字元範圍寫入資料流。Writes a character span to the stream.

Write(Single)

將 4 位元組浮點數值的文字表示寫入文字資料流。Writes the text representation of a 4-byte floating-point value to the text stream.

(繼承來源 TextWriter)
Write(String)

將字串寫入資料流。Writes a string to the stream.

Write(String, Object)

使用與 Format(String, Object) 方法相同的語意,將格式化字串寫入資料流。Writes a formatted string to the stream, using the same semantics as the Format(String, Object) method.

Write(String, Object, Object)

使用與 Format(String, Object, Object) 方法相同的語意,將格式化字串寫入資料流。Writes a formatted string to the stream using the same semantics as the Format(String, Object, Object) method..

Write(String, Object, Object, Object)

使用與 Format(String, Object, Object, Object) 方法相同的語意,將格式化字串寫入資料流。Writes a formatted string to the stream, using the same semantics as the Format(String, Object, Object, Object) method.

Write(String, Object[])

使用與 Format(String, Object[]) 方法相同的語意,將格式化字串寫入資料流。Writes a formatted string to the stream, using the same semantics as the Format(String, Object[]) method.

Write(StringBuilder)

將字串產生器寫入文字資料流。Writes a string builder to the text stream.

(繼承來源 TextWriter)
Write(UInt32)

將 4 位元組不帶正負號的整數文字表示寫入文字資料流。Writes the text representation of a 4-byte unsigned integer to the text stream.

(繼承來源 TextWriter)
Write(UInt64)

將 8 位元組帶不正負號的整數文字表示寫入文字資料流。Writes the text representation of an 8-byte unsigned integer to the text stream.

(繼承來源 TextWriter)
WriteAsync(Char)

以非同步方式將字元寫入至資料流。Asynchronously writes a character to the stream.

WriteAsync(Char[])

以非同步方式將字元陣列寫入文字資料流。Writes a character array to the text stream asynchronously.

(繼承來源 TextWriter)
WriteAsync(Char[], Int32, Int32)

以非同步方式將字元的子陣列寫入資料流。Asynchronously writes a subarray of characters to the stream.

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.

(繼承來源 TextWriter)
WriteLine()

將行結束字元寫入文字資料流。Writes a line terminator to the text stream.

(繼承來源 TextWriter)
WriteLine(Boolean)

Boolean 值的文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a Boolean value to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Char)

將字元寫入文字資料流,後接行結束字元。Writes a character to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Char[])

將字元的陣列寫入文字資料流,後接行結束字元。Writes an array of characters to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Char[], Int32, Int32)

將字元的子陣列寫入文字資料流,後接行結束字元。Writes a subarray of characters to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Decimal)

將十進位值的文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a decimal value to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Double)

將 8 位元組浮點數值的文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a 8-byte floating-point value to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Int32)

將 4 位元組帶正負號的整數文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Int64)

將 8 位元組帶正負號的整數文字表示寫入文字資料流,後接行結束字元。Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(Object)

藉由呼叫該物件上的 ToString 方法,後接行結束字元,將物件的文字表示寫入文字資料流。Writes the text representation of an object to the text stream, by calling the ToString method on that object, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(ReadOnlySpan<Char>)

將字元範圍的文字表示寫入資料流,後接行結束字元。Writes the text representation of a character span to the stream, followed by a line terminator.

WriteLine(Single)

將 4 位元組浮點數值的文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(String)

將字串寫入資料流,後接行結束字元。Writes a string to the stream, followed by a line terminator.

WriteLine(String, Object)

使用與 Format(String, Object) 方法相同的語意,將格式化字串和新行寫入資料流。Writes a formatted string and a new line to the stream, using the same semantics as the Format(String, Object) method.

WriteLine(String, Object, Object)

使用與 Format(String, Object, Object) 方法相同的語意,將格式化字串和新行寫入資料流。Writes a formatted string and a new line to the stream, using the same semantics as the Format(String, Object, Object) method.

WriteLine(String, Object, Object, Object)

使用與 Format(String, Object) 相同的語意,寫出資料流中的格式化字串和新行。Writes out a formatted string and a new line to the stream, using the same semantics as Format(String, Object).

WriteLine(String, Object[])

使用與 Format(String, Object) 相同的語意,寫出資料流中的格式化字串和新行。Writes out a formatted string and a new line to the stream, using the same semantics as Format(String, Object).

WriteLine(StringBuilder)

將字串產生器的文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a string builder to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(UInt32)

將 4 位元組不帶正負號的整數文字表示寫入文字資料流,後接行結束字元。Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLine(UInt64)

將 8 位元組不帶正負號的整數文字表示寫入文字資料流,後接行結束字元。Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
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[])

以非同步方式將字元的陣列寫入文字資料流,後接行結束字元。Asynchronously writes an array of characters to the text stream, followed by a line terminator.

(繼承來源 TextWriter)
WriteLineAsync(Char[], Int32, Int32)

以非同步方式將字元的子陣列寫入資料流,後接行結束字元。Asynchronously writes a subarray of characters to the stream, followed by a line terminator.

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.

(繼承來源 TextWriter)

明確介面實作

IDisposable.Dispose()

如需這個成員的說明,請參閱 Dispose()For a description of this member, see Dispose().

(繼承來源 TextWriter)

適用於

另請參閱