StreamReader Class

Definition

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

public ref class StreamReader : System::IO::TextReader
public class StreamReader : System.IO.TextReader
[System.Serializable]
public 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
Inheritance
StreamReader
Inheritance
Attributes

Examples

下面的示例使用 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.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.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.

Remarks

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.

Important

此类型实现 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.

除非另行指定,否则 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.SynchronizedSee TextReader.Synchronized for a thread-safe wrapper.

Read(Char[], Int32, Int32)Write(Char[], Int32, Int32) 方法重载读取并写入 count 参数指定的字符数。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.

Note

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.

Constructors

StreamReader(Stream)

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

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 类的一个新实例。Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

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 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小。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 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小,有选择性的打开流。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 类的新实例。Initializes a new instance of the StreamReader class for the specified file name.

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 类的一个新实例。Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

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 类的新实例,带有指定字符编码、字节顺序标记检测选项和缓冲区大小。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.

Fields

Null

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

Properties

BaseStream

返回基础流。Returns the underlying stream.

CurrentEncoding

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

EndOfStream

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

Methods

Close()

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

Close()

关闭 TextReader 并释放与该 TextReader 关联的所有系统资源。Closes the TextReader and releases any system resources associated with the TextReader.

(Inherited from TextReader)
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()

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

Dispose()

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

(Inherited from TextReader)
Dispose(Boolean)

关闭基础流,释放 StreamReader 使用的未托管资源,同时还可以根据需要释放托管资源。Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

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

(Inherited from Object)
MemberwiseClone(Boolean)

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

(Inherited from MarshalByRefObject)
Peek()

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

Read()

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

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

将当前流中的字符读入范围。Reads the characters from the current stream into a span.

Read(Span<Char>)

从当前读取器中读取字符,并将数据写入指定的缓冲区。Reads the characters from the current reader and writes the data to the specified buffer.

(Inherited from TextReader)
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(Char[], Int32, Int32)

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

(Inherited from TextReader)
ReadAsync(Memory<Char>, CancellationToken)

将当前流中的字符异步读入内存块。Asynchronously reads the characters from the current stream into a memory block.

ReadAsync(Memory<Char>, CancellationToken)

将当前流中的字符异步读入内存块。Asynchronously reads the characters from the current stream into a memory block.

(Inherited from TextReader)
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(Char[], Int32, Int32)

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

(Inherited from TextReader)
ReadBlock(Span<Char>)

从当前流中读取字符并将数据写入缓冲区。Reads the characters from the current stream and writes the data to a buffer.

ReadBlock(Span<Char>)

从当前流中读取字符并将数据写入缓冲区。Reads the characters from the current stream and writes the data to a buffer.

(Inherited from TextReader)
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(Char[], Int32, Int32)

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

(Inherited from TextReader)
ReadBlockAsync(Memory<Char>, CancellationToken)

从当前流中异步读取字符并将数据写入缓冲区。Asynchronously reads the characters from the current stream and writes the data to a buffer.

ReadBlockAsync(Memory<Char>, CancellationToken)

从当前流中异步读取字符并将数据写入缓冲区。Asynchronously reads the characters from the current stream and writes the data to a buffer.

(Inherited from TextReader)
ReadLine()

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

ReadLineAsync()

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

ReadLineAsync()

异步读取一行字符并将数据作为字符串返回。Reads a line of characters asynchronously and returns the data as a string.

(Inherited from TextReader)
ReadToEnd()

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

ReadToEndAsync()

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

ReadToEndAsync()

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

(Inherited from TextReader)
ToString()

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

(Inherited from Object)

Explicit Interface Implementations

IDisposable.Dispose()

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

(Inherited from TextReader)

Applies to

See also