FileStream.ReadByte Method ()

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Reads a byte from the file and advances the read position one byte.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

Public Overrides Function ReadByte As Integer

Return Value

Type: System.Int32

The byte, cast to an Int32, or -1 if the end of the stream has been reached.

Exception Condition
NotSupportedException

The current stream does not support reading.

ObjectDisposedException

The current stream is closed.

This method overrides ReadByte.

System_CAPS_noteNote

Use the CanRead property to determine whether the current instance supports reading. For additional information, see CanRead.

Notes to Implementers:

The default implementation on Stream creates a new single-byte array and then calls Read. While this is formally correct, it is inefficient. 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.

For a list of common file and directory operations, see Common I-O Tasks.

The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

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

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
Show: