FileStream.ReadByte Метод

Определение

Считывает байт из файла и перемещает положение чтения на один байт.

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

Возвращаемое значение

Байт приводится к типу Int32 или -1, если достигнут конец потока.

Исключения

Текущий поток не поддерживает чтение.

Текущий поток закрыт.

Примеры

В следующем примере кода показано, как записать данные в файл в байтах, а затем проверить правильность записи данных.

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);
        }
    }
}
open System
open System.IO


let fileName = "Test#@@#.dat"

// Create random data to write to the file.
let dataArray = Array.zeroCreate 100000
Random.Shared.NextBytes dataArray

do
    use fileStream = new FileStream(fileName, FileMode.Create)
    // Write the data to the file, byte by byte.
    for i = 0 to dataArray.Length - 1 do
        fileStream.WriteByte dataArray[i]

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

    // Read and verify the data.
    for i in 0L .. fileStream.Length - 1L do
        if dataArray[int i] <> (fileStream.ReadByte() |> byte) then
            printfn "Error writing data."
            exit 1

    printfn $"The data was written to {fileStream.Name} and verified."
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

Комментарии

Этот метод переопределяет метод ReadByte.

Примечание

Используйте свойство , CanRead чтобы определить, поддерживает ли текущий экземпляр чтение. Дополнительные сведения см. в разделе CanRead.

Примечания для тех, кто наследует этот метод

Реализация по умолчанию в Stream создает новый однобайтовый массив, а затем вызывает .Read(Byte[], Int32, Int32) Хотя это формально правильно, это неэффективно. Любой поток с внутренним буфером должен переопределять этот метод и предоставлять гораздо более эффективную версию, которая считывает буфер напрямую, избегая выделения дополнительного массива при каждом вызове.

Список распространенных операций с файлами и каталогами см. в разделе Общие задачи ввода-вывода.

Применяется к

См. также раздел