StreamReader.Peek Yöntem

Tanım

Bir sonraki kullanılabilir karakteri döndürür ancak kullanmaz.

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

Döndürülenler

Okunacak sonraki karakteri temsil eden bir tamsayı veya okunacak karakter yoksa veya akış aramayı desteklemiyorsa -1.

Özel durumlar

G/Ç hatası oluşur.

Örnekler

Aşağıdaki kod örneği, dosyanın sonuna ulaşılana kadar bir dosyadaki satırları okur.

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

Açıklamalar

Peek yöntemi, dosyanın sonunun veya başka bir hatanın oluşup oluşmadığını belirlemek için bir tamsayı değeri döndürür. Bu, kullanıcının bir türe dönüştürmeden önce döndürülen değerin -1 olup olmadığını denetlemesine Char olanak tanır.

Bu yöntem geçersiz kılar TextReader.Peek.

Nesnenin StreamReader geçerli konumu tarafından Peekdeğiştirilmez.

Şunlara uygulanır

Ayrıca bkz.