StreamReader StreamReader StreamReader StreamReader Class

定義

實作以特定的編碼方式自位元組資料流讀取字元的 TextReaderImplements 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.

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.

注意

從讀取時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

空資料流周圍的 StreamReader 物件。A 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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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 所使用的 Unmanaged 資源,然後再選擇性釋放 Managed 資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 的淺層複本 (Shallow Copy)。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)

適用於

另請參閱