Lire en anglais

Partager via


BinaryReader.ReadByte Méthode

Définition

Lit l'octet suivant du flux actuel et avance la position actuelle du flux d'un octet.

public virtual byte ReadByte ();

Retours

Octet suivant lu dans le flux actuel.

Exceptions

La fin du flux est atteinte.

Le flux est fermé.

Une erreur d'E/S s'est produite.

Exemples

L’exemple de code suivant montre comment écrire des données binaires à l’aide de la mémoire comme magasin de stockage, puis vérifier que les données ont été écrites correctement.

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;

        // Create random data to write to the stream.
        byte[] writeArray = new byte[1000];
        new Random().NextBytes(writeArray);

        BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
        BinaryReader binReader =
            new BinaryReader(binWriter.BaseStream);

        try
        {
            // Write the data to the stream.
            Console.WriteLine("Writing the data.");
            for(i = 0; i < writeArray.Length; i++)
            {
                binWriter.Write(writeArray[i]);
            }

            // Set the stream position to the beginning of the stream.
            binReader.BaseStream.Position = 0;

            // Read and verify the data from the stream.
            for(i = 0; i < writeArray.Length; i++)
            {
                if(binReader.ReadByte() != writeArray[i])
                {
                    Console.WriteLine("Error writing the data.");
                    return;
                }
            }
            Console.WriteLine("The data was written and verified.");
        }

        // Catch the EndOfStreamException and write an error message.
        catch(EndOfStreamException e)
        {
            Console.WriteLine("Error writing the data.\n{0}",
                e.GetType().Name);
        }
    }
}

Remarques

BinaryReader ne restaure pas la position du fichier après un échec de lecture.

En raison de conflits de mise en forme des données, l’utilisation de cette méthode avec les encodages suivants n’est pas recommandée :

  • UTF-7

  • ISO-2022-JP

  • ISCII

Pour obtenir la liste des tâches d’E/S courantes, consultez Tâches courantes d’E/S.

S’applique à

Voir aussi