StreamReader.ReadLine Método

Definição

Lê uma linha de caracteres do fluxo atual e retorna os dados como uma cadeia de caracteres.

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

Retornos

String

A próxima linha do fluxo de entrada, ou null, se o final do fluxo de entrada for atingido.

Exceções

Não há memória suficiente para alocar um buffer à cadeia de caracteres retornada.

Ocorre um erro de E/S.

Exemplos

O exemplo de código a seguir lê as linhas de um arquivo até que o final do arquivo seja atingido.

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::WriteLine( sr->ReadLine() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
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

Comentários

Uma linha é definida como uma sequência de caracteres seguida por uma alimentação de linha ("\n"), um retorno de carro ("\r") ou um retorno de carro seguido imediatamente por uma alimentação de linha ("\r\n"). A cadeia de caracteres retornada não contém o retorno de carro de terminação ou o feed de linha. O valor retornado é null se o final do fluxo de entrada for atingido.

Este método substitui TextReader.ReadLine.

Se o método atual lançar um OutOfMemoryException , a posição do leitor no objeto subjacente Stream será avançada pelo número de caracteres que o método foi capaz de ler, mas os caracteres já lidos no buffer interno ReadLine serão descartados. Se você manipular a posição do fluxo subjacente depois de ler dados no buffer, a posição do fluxo subjacente poderá não corresponder à posição do buffer interno. Para redefinir o buffer interno, chame o DiscardBufferedData método; no entanto, esse método reduz o desempenho e deve ser chamado somente quando absolutamente necessário.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.

Aplica-se a

Confira também