StreamReader.Peek 方法

定義

返回下一個可用角色,但不會消耗該角色。

public:
 override int Peek();
public override int Peek();
override this.Peek : unit -> int
Public Overrides Function Peek () As Integer

傳回

一個整數代表下一個要讀取的字元,或 -1 如果沒有字元可讀或串流不支援尋題。

例外狀況

發生 I/O 錯誤。

範例

以下程式碼範例會讀取檔案中的行數,直到到達檔案的末尾。

using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {

                while (sr.Peek() > -1)
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() > -1
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

備註

該方法回 Peek 傳一個整數值,以判斷檔案是否已結束或發生其他錯誤。 這讓使用者能先確認回傳值是否 -1,然後再將其鑄造成型 Char 別。

這個方法會覆寫 TextReader.Peek

物體目前的位置 StreamReader 不會因 Peek而改變。

適用於

另請參閱