StreamReader.Peek Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Restituisce il carattere disponibile successivo, ma non lo utilizza.
public:
override int Peek();
public override int Peek();
override this.Peek : unit -> int
Public Overrides Function Peek () As Integer
Valori restituiti
Intero che rappresenta il carattere successivo da leggere o -1 se non sono presenti caratteri da leggere o se il flusso non supporta la ricerca.
Eccezioni
Si verifica un errore di I/O.
Esempio
L'esempio di codice seguente legge le righe da un file fino al raggiungimento della fine del file.
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
Commenti
Il Peek metodo restituisce un valore intero per determinare se la fine del file o un altro errore si è verificato. In questo modo un utente può prima controllare se il valore restituito è -1 prima di eseguire il cast a un Char tipo.
Questo metodo esegue l'override di TextReader.Peek.
La posizione corrente dell'oggetto StreamReader non viene modificata da Peek.