StreamReader.ReadLine メソッド

定義

現在のストリームから 1 行の文字を読み取り、データを文字列として返します。

public:
 override System::String ^ ReadLine();
public override string ReadLine();
public override string? ReadLine();
override this.ReadLine : unit -> string
Public Overrides Function ReadLine () As String

返品

入力ストリームの次の行、または入力ストリームの末尾に達した場合に null します。

例外

返された文字列にバッファーを割り当てるためのメモリが不足しています。

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() >= 0)
                {
                    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() >= 0
                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

注釈

行は、一連の文字の後に改行 ("\n")、復帰 ("\r")、または改行 ("\r\n") が続く復帰として定義されます。 返される文字列には、終端復帰または改行は含まれません。 入力ストリームの末尾に達した場合、戻り値は null されます。

ストリームが改行 シーケンスで終わる場合、追加の空行は返されません。 たとえば、"line1\nline2\n"を含むストリームでは、"line1\nline2"を含むストリームと同じ 2 行 ("line1""line2") が生成されます。

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

現在のメソッドが OutOfMemoryExceptionをスローした場合、基になる Stream オブジェクト内のリーダーの位置は、メソッドが読み取ることができた文字数だけ進みますが、内部 ReadLine バッファーに既に読み込まれている文字は破棄されます。 バッファーへのデータの読み取り後に基になるストリームの位置を操作すると、基になるストリームの位置が内部バッファーの位置と一致しない可能性があります。 内部バッファーをリセットするには、 DiscardBufferedData メソッドを呼び出します。ただし、このメソッドはパフォーマンスを低下させ、絶対に必要な場合にのみ呼び出す必要があります。

一般的な I/O タスクの一覧については、「 一般的な I/O タスク」を参照してください。

適用対象

こちらもご覧ください