StreamReader StreamReader StreamReader StreamReader Class

定义

实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。Implements a TextReader that reads characters from a byte stream in a particular encoding.

public ref class StreamReader : System::IO::TextReader
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class StreamReader : System.IO.TextReader
type StreamReader = class
    inherit TextReader
Public Class StreamReader
Inherits TextReader
继承
属性

示例

下面的示例使用的StreamReader实例读取文件中的文本。The following example uses an instance of StreamReader to read text from a file. 在此示例中使用的构造函数不支持在应用Windows 应用商店Windows Store程序中使用。The constructor used in this example is not supported for use in Windows 应用商店Windows Store Apps.

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
      try
      {
         String^ line;
         
         // Read and display lines from the file until the end of 
         // the file is reached.
         while ( line = sr->ReadLine() )
         {
            Console::WriteLine( line );
         }
      }
      finally
      {
         if ( sr )
            delete (IDisposable^)sr;
      }
   }
   catch ( Exception^ e ) 
   {
      // Let the user know what went wrong.
      Console::WriteLine( "The file could not be read:" );
      Console::WriteLine( e->Message );
   }
}
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Class

下面的示例实例化StreamReader一个对象并调用ReadAsync其方法以异步读取文件。The following example instantiates a StreamReader object and calls its ReadAsync method to read a file asynchronously.

using System;
using System.IO;
using System.Threading.Tasks;

class Example
{
    static async Task Main()
    {
        await ReadAndDisplayFilesAsync();
    }

    static async Task ReadAndDisplayFilesAsync()
    {
        String filename = "TestFile1.txt";
        Char[] buffer;
        
        using (var sr = new StreamReader(filename)) {
            buffer = new Char[(int)sr.BaseStream.Length];
            await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
        }

        Console.WriteLine(new String(buffer));
    }
}
// The example displays the following output:
//       This is the first line of text in a relatively short file.
//       This is the second line.
//       This is the third line.
//       This is the fourth and final line.
Imports System
Imports System.IO
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
        ReadAndDisplayFilesAsync()
    End Sub

    Private Async Sub ReadAndDisplayFilesAsync()
        Dim filename As String = "TestFile1.txt"
        Dim buffer() As Char
        
        Using sr As New StreamReader(filename)
            ReDim buffer(CInt(sr.BaseStream.Length))
            Await sr.ReadAsync(buffer, 0, CInt(sr.BaseStream.Length))
        End Using

        Console.WriteLine(New String(buffer))
    End Sub
End Module
' The example displays the following output:
'       This is the first line of text in a relatively short file.
'       This is the second line.
'       This is the third line.
'       This is the fourth and final line.

注解

StreamReader设计用于特定编码的字符输入, 而Stream类用于字节输入和输出。StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. StreamReader用于读取标准文本文件中的行信息。Use StreamReader for reading lines of information from a standard text file.

重要

此类型实现IDisposable接口。This type implements the IDisposable interface. 在使用完类型后,您应直接或间接释放类型。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接Dispose释放类型, 请try / catch在块中调用其方法。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.

StreamReader除非另外指定, 否则默认为 UTF-8 编码, 而不是默认为当前系统的 ANSI 代码页。StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 正确地处理 Unicode 字符, 并为操作系统的本地化版本提供一致的结果。UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system. 如果使用CurrentEncoding属性获取当前字符编码, 则该值在第一Read种方法之后才是可靠的, 因为在首次调用Read方法之前不会进行编码自动检测。If you get the current character encoding using the CurrentEncoding property, the value is not reliable until after the first Read method, since encoding auto detection is not done until the first call to a Read method.

默认情况下, StreamReader不是线程安全的。By default, a StreamReader is not thread safe. 有关TextReader.Synchronized线程安全包装, 请参阅。See TextReader.Synchronized for a thread-safe wrapper.

和方法重载读取并写入count参数所指定的字符数。 Write(Char[], Int32, Int32) Read(Char[], Int32, Int32)The Read(Char[], Int32, Int32) and Write(Char[], Int32, Int32) method overloads read and write the number of characters specified by the count parameter. 这些将从BufferedStream.ReadBufferedStream.Write中区分, 它们可读取和写入count参数指定的字节数。These are to be distinguished from BufferedStream.Read and BufferedStream.Write, which read and write the number of bytes specified by the count parameter. BufferedStream使用方法仅用于读取和写入整数个字节数组元素。Use the BufferedStream methods only for reading and writing an integral number of byte array elements.

备注

从读取时Stream, 使用与流的内部缓冲区大小相同的缓冲区会更有效。When reading from a Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.

有关常见 i/o 任务的列表, 请参阅常见 I/o 任务For a list of common I/O tasks, see Common I/O Tasks.

构造函数

StreamReader(Stream) StreamReader(Stream) StreamReader(Stream) StreamReader(Stream)

为指定的流初始化 StreamReader 类的新实例。Initializes a new instance of the StreamReader class for the specified stream.

StreamReader(Stream, Boolean) StreamReader(Stream, Boolean) StreamReader(Stream, Boolean) StreamReader(Stream, Boolean)

用指定的字节顺序标记检测选项,为指定的流初始化 StreamReader 类的一个新实例。Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.

StreamReader(Stream, Encoding) StreamReader(Stream, Encoding) StreamReader(Stream, Encoding) StreamReader(Stream, Encoding)

用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例。Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

StreamReader(Stream, Encoding, Boolean) StreamReader(Stream, Encoding, Boolean) StreamReader(Stream, Encoding, Boolean) StreamReader(Stream, Encoding, Boolean)

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码和字节顺序标记检测选项。Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.

StreamReader(Stream, Encoding, Boolean, Int32) StreamReader(Stream, Encoding, Boolean, Int32) StreamReader(Stream, Encoding, Boolean, Int32) StreamReader(Stream, Encoding, Boolean, Int32)

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小。Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.

StreamReader(Stream, Encoding, Boolean, Int32, Boolean) StreamReader(Stream, Encoding, Boolean, Int32, Boolean) StreamReader(Stream, Encoding, Boolean, Int32, Boolean) StreamReader(Stream, Encoding, Boolean, Int32, Boolean)

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小,有选择性的打开流。Initializes a new instance of the StreamReader class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.

StreamReader(String) StreamReader(String) StreamReader(String) StreamReader(String)

为指定的文件名初始化 StreamReader 类的新实例。Initializes a new instance of the StreamReader class for the specified file name.

StreamReader(String, Boolean) StreamReader(String, Boolean) StreamReader(String, Boolean) StreamReader(String, Boolean)

为指定的文件名初始化 StreamReader 类的新实例,带有指定的字节顺序标记检测选项。Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.

StreamReader(String, Encoding) StreamReader(String, Encoding) StreamReader(String, Encoding) StreamReader(String, Encoding)

用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

StreamReader(String, Encoding, Boolean) StreamReader(String, Encoding, Boolean) StreamReader(String, Encoding, Boolean) StreamReader(String, Encoding, Boolean)

为指定的文件名初始化 StreamReader 类的新实例,带有指定的字符编码和字节顺序标记检测选项。Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.

StreamReader(String, Encoding, Boolean, Int32) StreamReader(String, Encoding, Boolean, Int32) StreamReader(String, Encoding, Boolean, Int32) StreamReader(String, Encoding, Boolean, Int32)

为指定的文件名初始化 StreamReader 类的新实例,带有指定字符编码、字节顺序标记检测选项和缓冲区大小。Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.

字段

Null Null Null Null

空流周围的 StreamReaderA StreamReader object around an empty stream.

属性

BaseStream BaseStream BaseStream BaseStream

返回基础流。Returns the underlying stream.

CurrentEncoding CurrentEncoding CurrentEncoding CurrentEncoding

获取当前 StreamReader 对象正在使用的当前字符编码。Gets the current character encoding that the current StreamReader object is using.

EndOfStream EndOfStream EndOfStream EndOfStream

获取一个值,该值表示当前的流位置是否在流的末尾。Gets a value that indicates whether the current stream position is at the end of the stream.

方法

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

关闭 StreamReader 对象和基础流,并释放与读取器关联的所有系统资源。Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

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)
DiscardBufferedData() DiscardBufferedData() DiscardBufferedData() DiscardBufferedData()

清除内部缓冲区。Clears the internal buffer.

Dispose() Dispose() Dispose() Dispose()

释放由 TextReader 对象使用的所有资源。Releases all resources used by the TextReader object.

(Inherited from TextReader)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

关闭基础流,释放 StreamReader 使用的未托管资源,同时还可以根据需要释放托管资源。Closes the underlying stream, releases the unmanaged resources used by the StreamReader, 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)
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()

获取当前实例的 TypeGets 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()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

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

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Peek() Peek() Peek() Peek()

返回下一个可用的字符,但不使用它。Returns the next available character but does not consume it.

Read() Read() Read() Read()

读取输入流中的下一个字符并使该字符的位置提升一个字符。Reads the next character from the input stream and advances the character position by one character.

Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

从当前流中将指定的最多个字符读到指定索引位置开始的缓冲区。Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

Read(Span<Char>) Read(Span<Char>) Read(Span<Char>) Read(Span<Char>)
ReadAsync(Char[], Int32, Int32) ReadAsync(Char[], Int32, Int32) ReadAsync(Char[], Int32, Int32) ReadAsync(Char[], Int32, Int32)

从当前流中异步读取指定的最大字符,并且从指定的索引位置开始将该数据写入缓冲区。Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.

ReadAsync(Memory<Char>, CancellationToken) ReadAsync(Memory<Char>, CancellationToken) ReadAsync(Memory<Char>, CancellationToken) ReadAsync(Memory<Char>, CancellationToken)
ReadBlock(Char[], Int32, Int32) ReadBlock(Char[], Int32, Int32) ReadBlock(Char[], Int32, Int32) ReadBlock(Char[], Int32, Int32)

从当前流中读取指定数目的字符并从指定索引开始将该数据写入缓冲区。Reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index.

ReadBlock(Span<Char>) ReadBlock(Span<Char>) ReadBlock(Span<Char>) ReadBlock(Span<Char>)
ReadBlockAsync(Char[], Int32, Int32) ReadBlockAsync(Char[], Int32, Int32) ReadBlockAsync(Char[], Int32, Int32) ReadBlockAsync(Char[], Int32, Int32)

从当前流中异步读取指定的最大字符,并且从指定的索引位置开始将该数据写入缓冲区。Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.

ReadBlockAsync(Memory<Char>, CancellationToken) ReadBlockAsync(Memory<Char>, CancellationToken) ReadBlockAsync(Memory<Char>, CancellationToken) ReadBlockAsync(Memory<Char>, CancellationToken)
ReadLine() ReadLine() ReadLine() ReadLine()

从当前流中读取一行字符并将数据作为字符串返回。Reads a line of characters from the current stream and returns the data as a string.

ReadLineAsync() ReadLineAsync() ReadLineAsync() ReadLineAsync()

从当前流中异步读取一行字符并将数据作为字符串返回。Reads a line of characters asynchronously from the current stream and returns the data as a string.

ReadToEnd() ReadToEnd() ReadToEnd() ReadToEnd()

从流的当前位置到末尾读取所有字符。Reads all characters from the current position to the end of the stream.

ReadToEndAsync() ReadToEndAsync() ReadToEndAsync() ReadToEndAsync()

异步读取从当前位置到流的结尾的所有字符并将它们作为一个字符串返回。Reads all characters from the current position to the end of the stream asynchronously and returns them as one string.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

有关此成员的说明,请参见 Dispose()For a description of this member, see Dispose().

(Inherited from TextReader)

适用于

另请参阅