StreamReader.Peek メソッド

定義

次に使用できる文字を返しますが、使用しません。

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

返品

読み取る次の文字を表す整数。読み取る文字がない場合、またはストリームがシークをサポートしていない場合に -1。

例外

I/O エラーが発生しました。

次のコード例では、ファイルの末尾に達するまでファイルから行を読み取ります。

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

注釈

Peek メソッドは、ファイルの末尾または別のエラーが発生したかどうかを判断するために整数値を返します。 これにより、ユーザーは、 Char 型にキャストする前に、返された値が -1 されているかどうかを最初に確認できます。

このメソッドは、TextReader.Peek をオーバーライドします。

StreamReader オブジェクトの現在の位置は、Peekによって変更されません。

適用対象

こちらもご覧ください