StreamReader.Peek Método

Definición

Devuelve el siguiente carácter disponible, pero no lo consume.

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

Devoluciones

Entero que representa el siguiente carácter que se va a leer o -1 si no hay caracteres que se van a leer o si la secuencia no admite la búsqueda.

Excepciones

Se produce un error de E/S.

Ejemplos

En el ejemplo de código siguiente se leen las líneas de un archivo hasta que se alcanza el final del archivo.

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

Comentarios

El Peek método devuelve un valor entero para determinar si se ha producido el final del archivo u otro error. Esto permite a un usuario comprobar primero si el valor devuelto es -1 antes de convertirlo en un Char tipo.

Este método invalida TextReader.Peek.

La posición actual del StreamReader objeto no cambia por Peek.

Se aplica a

Consulte también