StreamReader.Read Método

Definición

Lee el siguiente carácter o conjunto de caracteres del flujo de entrada.Reads the next character or next set of characters from the input stream.

Sobrecargas

Read()

Lee el siguiente carácter del flujo de entrada y hace avanzar la posición de los caracteres en un carácter.Reads the next character from the input stream and advances the character position by one character.

Read(Span<Char>)
Read(Char[], Int32, Int32)

Lee un máximo especificado de caracteres de la secuencia actual en un búfer, comenzando en el índice especificado.Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

Read()

Lee el siguiente carácter del flujo de entrada y hace avanzar la posición de los caracteres en un carácter.Reads the next character from the input stream and advances the character position by one character.

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

Devoluciones

El siguiente carácter del flujo de entrada que se representa como Int32 ó -1 si no hay más caracteres disponibles.The next character from the input stream represented as an Int32 object, or -1 if no more characters are available.

Excepciones

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

Ejemplos

En el ejemplo de código siguiente se muestra un uso Read simple del método.The following code example demonstrates a simple use of the Read method.

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::Write( (Char)sr->Read() );
         }
      }
      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.Write((char)sr.Read());
                }
            }
        } 
        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.Write(Convert.ToChar(sr.Read()))
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

En el ejemplo de código siguiente se muestra cómo leer un Read() solo carácter mediante la sobrecarga del método, dando formato al resultado entero ASCII como decimal y hexadecimal.The following code example demonstrates reading a single character using the Read() method overload, formatting the ASCII integer output as decimal and hexadecimal.

using namespace System;
using namespace System::IO;
int main()
{
   
   //Create a FileInfo instance representing an existing text file.
   FileInfo^ MyFile = gcnew FileInfo( "c:\\csc.txt" );
   
   //Instantiate a StreamReader to read from the text file.
   StreamReader^ sr = MyFile->OpenText();
   
   //Read a single character.
   int FirstChar = sr->Read();
   
   //Display the ASCII number of the character read in both decimal and hexadecimal format.
   Console::WriteLine( "The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar );
   
   //
   sr->Close();
}

using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}
Imports System.IO

Class StrmRdrRead
   
   Public Shared Sub Main()
      'Create a FileInfo instance representing an existing text file.
      Dim MyFile As New FileInfo("c:\csc.txt")
      'Instantiate a StreamReader to read from the text file.
      Dim sr As StreamReader = MyFile.OpenText()
      'Read a single character.
      Dim FirstChar As Integer = sr.Read()
      'Display the ASCII number of the character read in both decimal and hexadecimal format.
      Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
      sr.Close()
   End Sub
End Class

Comentarios

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

Este método devuelve un entero para que pueda devolver-1 si se ha alcanzado el final de la secuencia.This method returns an integer so that it can return -1 if the end of the stream has been reached. 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.

Consulte también:

Read(Span<Char>)

public:
 override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer

Parámetros

buffer
Span<Char>

Devoluciones

Read(Char[], Int32, Int32)

Lee un máximo especificado de caracteres de la secuencia actual en un búfer, comenzando en el índice especificado.Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

public:
 override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

Parámetros

buffer
Char[]

Cuando este método devuelve un valor, contiene la matriz de caracteres especificada con los valores comprendidos entre index y (índice + recuento - 1) reemplazada por los caracteres leídos del origen actual.When this method returns, contains the specified character array with the values between index and (index + count - 1) replaced by the characters read from the current source.

index
Int32

Índice de buffer en el que comenzará la escritura.The index of buffer at which to begin writing.

count
Int32

Número máximo de caracteres que se van a leer.The maximum number of characters to read.

Devoluciones

Número de caracteres leídos. Si se llega al final de la secuencia y no se leyó ningún dato es 0.The number of characters that have been read, or 0 if at the end of the stream and no data was read. El número será menor o igual que el parámetro count, dependiendo de si los datos están disponibles dentro de la secuencia.The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

Excepciones

La longitud del búfer menos index es menor que count.The buffer length minus index is less than count.

buffer es null.buffer is null.

index o count es negativo.index or count is negative.

Se produce un error de E/S, como el cierre de la secuencia.An I/O error occurs, such as the stream is closed.

Ejemplos

En el ejemplo de código siguiente se leen cinco caracteres a la vez hasta que se alcanza el final del archivo.The following code example reads five characters at a time 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
      {
         //This is an arbitrary size for this example.
         array<Char>^c = nullptr;
         while ( sr->Peek() >= 0 )
         {
            c = gcnew array<Char>(5);
            sr->Read( c, 0, c->Length );
            
            //The output will look odd, because
            //only five characters are read at a time.
            Console::WriteLine( c );
         }
      }
      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 is an arbitrary size for this example.
                char[] c = null;

                while (sr.Peek() >= 0) 
                {
                    c = new char[5];
                    sr.Read(c, 0, c.Length);
                    //The output will look odd, because
                    //only five characters are read at a time.
                    Console.WriteLine(c);
                }
            }
        } 
        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
                'This is an arbitrary size for this example.
                Dim c(5) As Char
                sr.Read(c, 0, c.Length)
                'The output will look odd, because
                'only five characters are read at a time.
                Console.WriteLine(c)
            Loop
            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.Read.This method overrides TextReader.Read.

Este método devuelve un entero para que pueda devolver 0 si se alcanza el final de la secuencia.This method returns an integer so that it can return 0 if the end of the stream has been reached.

Cuando se usa Read el método, es más eficaz utilizar un búfer que tenga el mismo tamaño que el búfer interno de la secuencia, donde el búfer interno se establece en el tamaño de bloque deseado y siempre debe leerse menos que el tamaño del bloque.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, where the internal buffer is set to your desired block size, and to always read less than the block size. Si el tamaño del búfer interno no se especificó cuando se construyó la secuencia, su tamaño predeterminado es 4 kilobytes (4096 bytes).If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). 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.

Este método devuelve después de que se lea el número de caracteres count especificado por el parámetro o hasta que se alcance el final del archivo.This method returns after either the number of characters specified by the count parameter are read, or the end of the file is reached. ReadBlockes una versión de bloqueo Readde.ReadBlock is a blocking version of Read.

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.

Consulte también:

Se aplica a