C# FileStream ReadByte

Description

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

Syntax

FileStream.ReadByte has the following syntax.


public override int ReadByte()

Returns

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

Example

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 System;//www.  j av  a 2  s. c om
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test.dat";
        byte[] dataArray = new byte[100];
        new Random().NextBytes(dataArray);
        using(FileStream fileStream = new FileStream(fileName, FileMode.Create))
        {
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }
            fileStream.Seek(0, SeekOrigin.Begin);
            for(int i = 0; i < fileStream.Length; i++)
            {
                Console.WriteLine(fileStream.ReadByte());
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter