StreamReader.Peek Metoda

Definicja

Zwraca następny dostępny znak, ale nie używa go.

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

Zwraca

Liczba całkowita reprezentująca następny znak do odczytu lub -1, jeśli nie ma znaków do odczytania lub jeśli strumień nie obsługuje wyszukiwania.

Wyjątki

Występuje błąd we/wy.

Przykłady

Poniższy przykład kodu odczytuje wiersze z pliku do końca pliku.

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

Uwagi

Metoda Peek zwraca wartość całkowitą w celu określenia, czy koniec pliku, czy inny błąd wystąpił. Dzięki temu użytkownik może najpierw sprawdzić, czy zwrócona wartość jest -1 przed oddaniem jej do Char typu.

Ta metoda zastępuje metodę TextReader.Peek.

Bieżące położenie StreamReader obiektu nie jest zmieniane przez Peek.

Dotyczy

Zobacz też