StreamReader.ReadLine StreamReader.ReadLine StreamReader.ReadLine StreamReader.ReadLine Method

Definición

Lee una línea de caracteres de la secuencia actual y devuelve los datos como una cadena.Reads a line of characters from the current stream and returns the data as a string.

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

Devoluciones

Línea siguiente del flujo de entrada, o null si se alcanza el final del flujo de entrada.The next line from the input stream, or null if the end of the input stream is reached.

Excepciones

No hay memoria suficiente para asignar un búfer para la cadena devuelta.There is insufficient memory to allocate a buffer for the returned string.

Error de E/S.An I/O error occurs.

Ejemplos

El siguiente ejemplo de código lee líneas de un archivo hasta que se alcanza el final del archivo.The following code example reads lines from a file until the end of the file is reached.

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
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

Comentarios

Una línea se define como fuente de una secuencia de caracteres seguida de una línea ("\n"), un retorno de carro "(\r) o un retorno de carro seguido inmediatamente por una línea de avance ("\r\n").A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). La cadena devuelta no contiene la terminación de retorno de carro o avance de línea.The string that is returned does not contain the terminating carriage return or line feed. El valor devuelto es null si se alcanza el final del flujo de entrada.The returned value is null if the end of the input stream is reached.

Este método invalida TextReader.ReadLine.This method overrides TextReader.ReadLine.

Si el método actual produce una OutOfMemoryException, la posición del lector en subyacente Stream objeto avanza por el número de caracteres que el método fue capaz de leer, pero los caracteres ya leídos en el interno ReadLine se descartan búfer .If the current method throws an OutOfMemoryException, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. Si manipula la posición de la secuencia subyacente después de leer los datos en el búfer, la posición de la secuencia subyacente podría no coincidir con la posición del búfer interno.If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. Para restablecer el búfer interno, llame a la DiscardBufferedData método; sin embargo, este método reduce el rendimiento y se debe llamar cuando sea absolutamente necesario.To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.

Para obtener una lista de tareas de E/S comunes, consulte tareas de E/S comunes.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a

Consulte también: