FileStream.ReadByte FileStream.ReadByte FileStream.ReadByte FileStream.ReadByte Method

Definición

Lee un byte del archivo y avanza la posición de lectura un byte.Reads a byte from the file and advances the read position one byte.

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

Devoluciones

El byte, convertido en un Int32, o -1 si se ha alcanzado el final de la secuencia.The byte, cast to an Int32, or -1 if the end of the stream has been reached.

Excepciones

La secuencia actual no admite lectura.The current stream does not support reading.

Se cierra la secuencia actual.The current stream is closed.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir datos en un archivo, byte por byte y, a continuación, comprobar que los datos se escribieron correctamente.The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

using namespace System;
using namespace System::IO;
int main()
{
   String^ fileName =  "Test@##@.dat";
   
   // Create random data to write to the file.
   array<Byte>^dataArray = gcnew array<Byte>(100000);
   (gcnew Random)->NextBytes( dataArray );
   FileStream^ fileStream = gcnew FileStream( fileName,FileMode::Create );
   try
   {
      
      // Write the data to the file, byte by byte.
      for ( int i = 0; i < dataArray->Length; i++ )
      {
         fileStream->WriteByte( dataArray[ i ] );

      }
      
      // Set the stream position to the beginning of the file.
      fileStream->Seek( 0, SeekOrigin::Begin );
      
      // Read and verify the data.
      for ( int i = 0; i < fileStream->Length; i++ )
      {
         if ( dataArray[ i ] != fileStream->ReadByte() )
         {
            Console::WriteLine( "Error writing data." );
            return  -1;
         }

      }
      Console::WriteLine( "The data was written to {0} "
      "and verified.", fileStream->Name );
   }
   finally
   {
      fileStream->Close();
   }

}

using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream  
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Text

Class FStream

    Shared Sub Main()

        Const fileName As String = "Test#@@#.dat"

        ' Create random data to write to the file.
        Dim dataArray(100000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(dataArray)

        Dim fileStream As FileStream = _
            new FileStream(fileName, FileMode.Create)
        Try

            ' Write the data to the file, byte by byte.
            For i As Integer = 0 To dataArray.Length - 1
                fileStream.WriteByte(dataArray(i))
            Next i

            ' Set the stream position to the beginning of the stream.
            fileStream.Seek(0, SeekOrigin.Begin)

            ' Read and verify the data.
            For i As Integer = 0 To _
                CType(fileStream.Length, Integer) - 1

                If dataArray(i) <> fileStream.ReadByte() Then
                    Console.WriteLine("Error writing data.")
                    Return
                End If
            Next i
            Console.WriteLine("The data was written to {0} " & _
                "and verified.", fileStream.Name)
        Finally
            fileStream.Close()
        End Try
    
    End Sub
End Class

Comentarios

Este método invalida ReadByte.This method overrides ReadByte.

Nota

Utilice la CanRead propiedad para determinar si la instancia actual admite operaciones de lectura.Use the CanRead property to determine whether the current instance supports reading. Para obtener información adicional, vea CanRead.For additional information, see CanRead.

Notas a los desarrolladores de herederos

La implementación predeterminada de Stream crea una nueva matriz de un solo byte y, Read(Byte[], Int32, Int32)a continuación, llama a.The default implementation on Stream creates a new single-byte array and then calls Read(Byte[], Int32, Int32). Aunque esto es correcto, no es eficaz.While this is formally correct, it is inefficient. Cualquier flujo con un búfer interno debe invalidar este método y proporcionar una versión mucho más eficaz que lea el búfer directamente, evitando la asignación de matriz adicional en cada llamada.Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

Para obtener una lista de operaciones comunes de archivos y directorios, vea tareas de e/s comunes.For a list of common file and directory operations, see Common I/O Tasks.

Se aplica a

Consulte también: