StreamWriter 类

定义

实现一个 TextWriter,使其以一种特定的编码向流中写入字符。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)]
[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. using使用对象的Dispose代码已完成时,该语句会自动对该对象调用。The 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)或。 StreamWriterTo 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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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()

清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。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()

检索控制此实例的生存期策略的当前生存期服务对象。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)

适用于

另请参阅