StreamReader 类

定义

实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。

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

示例

以下示例使用 的 StreamReader 实例从文件中读取文本。 不支持在 Windows 应用商店应用中使用此示例中使用的构造函数。

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 方法来异步读取文件。

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.

注解

StreamReader 设计用于特定编码中的字符输入,而 Stream 类设计用于字节输入和输出。 用于 StreamReader 从标准文本文件读取信息行。

重要

此类型实现 IDisposable 接口。 在使用完类型后,您应直接或间接释放类型。 若要直接释放类型,请在 try/catch 块中调用其 Dispose 方法。 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。

StreamReader 除非另行指定,否则默认为 UTF-8 编码,而不是默认为当前系统的 ANSI 代码页。 UTF-8 正确处理 Unicode 字符,并在操作系统的本地化版本上提供一致的结果。 如果使用 属性获取当前字符编码 CurrentEncoding ,则值在第一 ReadRead 方法之后才可靠,因为编码自动检测在首次调用方法之前不会完成。

默认情况下, StreamReader 不是线程安全的。 有关线程安全包装器,请参阅 TextReader.Synchronized

Read(Char[], Int32, Int32)Write(Char[], Int32, Int32) 方法重载读取和写入 参数count指定的字符数。 它们与 和 BufferedStream.WriteBufferedStream.Read分开来,后者读取和写入 参数指定的count字节数。 仅使用 BufferedStream 方法读取和写入整数个字节数组元素。

注意

Stream读取 时,使用与流内部缓冲区大小相同的缓冲区更高效。

有关常见 I/O 任务的列表,请参阅 常见 I/O 任务

构造函数

StreamReader(Stream)

为指定的流初始化 StreamReader 类的新实例。

StreamReader(Stream, Boolean)

用指定的字节顺序标记检测选项,为指定的流初始化 StreamReader 类的一个新实例。

StreamReader(Stream, Encoding)

用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例。

StreamReader(Stream, Encoding, Boolean)

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码和字节顺序标记检测选项。

StreamReader(Stream, Encoding, Boolean, Int32)

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小。

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

为指定的流初始化 StreamReader 类的新实例,带有指定的字符编码、字节顺序标记检测选项和缓冲区大小,有选择性的打开流。

StreamReader(String)

为指定的文件名初始化 StreamReader 类的新实例。

StreamReader(String, Boolean)

为指定的文件名初始化 StreamReader 类的新实例,带有指定的字节顺序标记检测选项。

StreamReader(String, Encoding)

用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。

StreamReader(String, Encoding, Boolean)

为指定的文件名初始化 StreamReader 类的新实例,带有指定的字符编码和字节顺序标记检测选项。

StreamReader(String, Encoding, Boolean, FileStreamOptions)

使用指定的字符编码、字节顺序标记检测选项并为指定的对象配置FileStreamOptions指定文件路径初始化 类的新实例StreamReader

StreamReader(String, Encoding, Boolean, Int32)

为指定的文件名初始化 StreamReader 类的新实例,带有指定字符编码、字节顺序标记检测选项和缓冲区大小。

StreamReader(String, FileStreamOptions)

使用默认编码为指定文件路径初始化 类的新实例 StreamReader ,启用文件开头的字节顺序标记检测,并使用指定的 FileStreamOptions 对象进行配置。

字段

Null

空流周围的 StreamReader

属性

BaseStream

返回基础流。

CurrentEncoding

获取当前 StreamReader 对象正在使用的当前字符编码。

EndOfStream

获取一个值,该值指示当前的流位置是否在流结尾。

方法

Close()

关闭 StreamReader 对象和基础流,并释放与读取器关联的所有系统资源。

Close()

关闭 TextReader 并释放与该 TextReader 关联的所有系统资源。

(继承自 TextReader)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
DiscardBufferedData()

清除内部缓冲区。

Dispose()

释放由 TextReader 对象使用的所有资源。

(继承自 TextReader)
Dispose(Boolean)

关闭基础流,释放 StreamReader 使用的未托管资源,同时还可以根据需要释放托管资源。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
Peek()

返回下一个可用字符,但不使用它。

Read()

读取输入流中的下一个字符并使该字符位置提升一个字符。

Read(Char[], Int32, Int32)

从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区。

Read(Span<Char>)

将当前流中的字符读入范围。

Read(Span<Char>)

从当前读取器中读取字符,并将数据写入指定的缓冲区。

(继承自 TextReader)
ReadAsync(Char[], Int32, Int32)

从当前流中异步读取指定的最大字符,并且从指定的索引位置开始将该数据写入缓冲区。

ReadAsync(Char[], Int32, Int32)

异步从当前文本读取器中读取指定最大字符数并从指定索引开始将该数据写入缓冲区。

(继承自 TextReader)
ReadAsync(Memory<Char>, CancellationToken)

将当前流中的字符异步读入内存块。

ReadAsync(Memory<Char>, CancellationToken)

将当前流中的字符异步读入内存块。

(继承自 TextReader)
ReadBlock(Char[], Int32, Int32)

从当前流中读取指定的最大字符数并从指定的索引位置开始将该数据写入缓冲区。

ReadBlock(Char[], Int32, Int32)

从当前文本读取器中读取指定的最大字符数并从指定索引处开始将该数据写入缓冲区。

(继承自 TextReader)
ReadBlock(Span<Char>)

从当前流中读取字符并将数据写入缓冲区。

ReadBlock(Span<Char>)

从当前流中读取字符并将数据写入缓冲区。

(继承自 TextReader)
ReadBlockAsync(Char[], Int32, Int32)

从当前流中异步读取指定的最大字符,并且从指定的索引位置开始将该数据写入缓冲区。

ReadBlockAsync(Char[], Int32, Int32)

异步从当前文本读取器中读取指定最大字符数并从指定索引开始将该数据写入缓冲区。

(继承自 TextReader)
ReadBlockAsync(Memory<Char>, CancellationToken)

从当前流中异步读取字符并将数据写入缓冲区。

ReadBlockAsync(Memory<Char>, CancellationToken)

从当前流中异步读取字符并将数据写入缓冲区。

(继承自 TextReader)
ReadLine()

从当前流中读取一行字符并将数据作为字符串返回。

ReadLineAsync()

从当前流中异步读取一行字符并将数据作为字符串返回。

ReadLineAsync()

异步读取一行字符并将数据作为字符串返回。

(继承自 TextReader)
ReadLineAsync(CancellationToken)

从当前流中异步读取一行字符并将数据作为字符串返回。

ReadLineAsync(CancellationToken)

异步读取一行字符并将数据作为字符串返回。

(继承自 TextReader)
ReadToEnd()

读取来自流的当前位置到结尾的所有字符。

ReadToEndAsync()

异步读取来自流的当前位置到结尾的所有字符并将它们作为一个字符串返回。

ReadToEndAsync()

异步读取从当前位置到文本读取器末尾的所有字符并将它们作为一个字符串返回。

(继承自 TextReader)
ReadToEndAsync(CancellationToken)

异步读取来自流的当前位置到结尾的所有字符并将它们作为一个字符串返回。

ReadToEndAsync(CancellationToken)

异步读取从当前位置到文本读取器末尾的所有字符并将它们作为一个字符串返回。

(继承自 TextReader)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

IDisposable.Dispose()

有关此成员的说明,请参见 Dispose()

(继承自 TextReader)

适用于

另请参阅