StreamReader.Peek Método

Definição

Devolve o próximo personagem disponível mas não o consome.

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

Devoluções

Um inteiro que representa o próximo carácter a ser lido, ou -1 se não houver caracteres a ler ou se o fluxo não suportar a procura.

Exceções

Ocorre um erro de E/S.

Exemplos

O exemplo de código seguinte lê linhas de um ficheiro até ao final do ficheiro.

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

Observações

O Peek método devolve um valor inteiro para determinar se ocorreu o fim do ficheiro ou outro erro. Isto permite ao utilizador verificar primeiro se o valor devolvido está -1 antes de o lançar para um Char tipo.

Este método substitui o TextReader.Peek.

A posição atual do StreamReader objeto não é alterada por Peek.

Aplica-se a

Ver também