StreamReader.ReadToEnd Método

Definición

Lee todos los caracteres desde la posición actual hasta el final de la secuencia.Reads all characters from the current position to the end of the stream.

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

Devoluciones

String

Resto de la secuencia, como una cadena, desde la posición actual hasta el final.The rest of the stream as a string, from the current position to the end. Si la posición actual se encuentra al final de la secuencia, devuelve una cadena vacía ("").If the current position is at the end of the stream, returns an empty string ("").

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

En el ejemplo de código siguiente se lee todo el proceso hasta el final de un archivo en una operación.The following code example reads all the way to the end of a file in one operation.

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
      {
         //This allows you to do one Read operation.
         Console::WriteLine( sr->ReadToEnd() );
      }
      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))
            {
                //This allows you to do one Read operation.
                Console.WriteLine(sr.ReadToEnd());
            }
        }
        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)

            'This allows you to do one Read operation.
            Console.WriteLine(sr.ReadToEnd())
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentarios

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

ReadToEnd funciona mejor cuando necesita leer toda la entrada desde la posición actual hasta el final de la secuencia.ReadToEnd works best when you need to read all the input from the current position to the end of the stream. Si se necesita más control sobre el número de caracteres que se leen de la secuencia, use la Read(Char[], Int32, Int32) sobrecarga del método, que generalmente da como resultado un mejor rendimiento.If more control is needed over how many characters are read from the stream, use the Read(Char[], Int32, Int32) method overload, which generally results in better performance.

ReadToEnd supone que el flujo sabe cuándo se ha alcanzado un final.ReadToEnd assumes that the stream knows when it has reached an end. En el caso de los protocolos interactivos en los que el servidor envía datos solo cuando se solicita y no cierra la conexión, ReadToEnd podría bloquearse indefinidamente porque no llega a un extremo y debe evitarse.For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.

Tenga en cuenta que cuando se usa el Read método, es más eficaz utilizar un búfer que tenga el mismo tamaño que el búfer interno de la secuencia.Note that when using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. Si el tamaño del búfer no se especificó cuando se construyó la secuencia, su tamaño predeterminado es de 4 kilobytes (4096 bytes).If the size of the buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes).

Si el método actual produce una excepción OutOfMemoryException , la posición del lector en el Stream objeto subyacente se avanza por el número de caracteres que el método puede leer, pero los caracteres ya leídos en el ReadLine búfer interno se descartan.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 al DiscardBufferedData método; sin embargo, este método reduce el rendimiento y solo 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 comunes de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Se aplica a