StreamReader 類別

定義

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

備註

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. 若要直接處置型別,請呼叫其 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.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 類別的新執行個體。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.

欄位

Null

空資料流周圍的 StreamReader 物件。A StreamReader object around an empty stream.

屬性

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.

方法

Close()

關閉 StreamReader 物件和基礎資料流,並釋放任何與讀取器相關聯的系統資源。Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
DiscardBufferedData()

清除內部緩衝區。Clears the internal buffer.

Dispose()

釋放由 TextReader 物件使用的所有資源。Releases all resources used by the TextReader object.

(繼承來源 TextReader)
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)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

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

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 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>)
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)
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>)
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)
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.

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.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

如需這個成員的說明,請參閱 Dispose()For a description of this member, see Dispose().

(繼承來源 TextReader)

適用於

另請參閱