Reading Bytes from a FileStream

FileStream defines two methods that read bytes from a file: ReadByte( ) and Read( ). To read a single byte from a file, use ReadByte( ), whose general form is shown here:
int ReadByte( )
Each time it is called, it reads a single byte from the file and returns it as an integer value. It returns –1 when the end of the file is encountered. Possible exceptions include NotSupportedException (the stream is not opened for input) and ObjectDisposedException (the stream is closed).
 
To read a block of bytes, use Read( ), which has this general form: int Read(byte[ ] array, int offset, int count) Read( ) attempts to read up to count bytes into array starting at array[offset]. It returns the number of bytes successfully read. An IOException is thrown if an I/O error occurs. Several
other types of exceptions are possible, including NotSupportedException, which is thrown if reading is not supported by the stream.

The following program uses ReadByte( ) to input and display the contents of a text file, the name of which is specified as a command-line argument. Note the program first checks that a filename has been specified before trying to open the file.

Example

using System;
using System.IO;

namespace ConsoleApplication1
{
    class ShowFile
    {
        static void Main(string[] args)
        {
            int i;
            FileStream fin;
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ShowFile File");
                return;
            }
            try
            {
                fin = new FileStream(args[0], FileMode.Open);
            }
            catch (IOException exc)
            {
                Console.WriteLine("Cannot Open File");
                Console.WriteLine(exc.Message);
                return; // File can't be opened, so stop the program.
            }
            // Read bytes until EOF is encountered.
            try
            {
                do
                {
                    i = fin.ReadByte();
                    if (i != -1) Console.Write((char)i);
                } while (i != -1);
            }
            catch (IOException exc)
            {
                Console.WriteLine("Error Reading File");
                Console.WriteLine(exc.Message);
            }
            finally
            {
                fin.Close();
            }
        }
    }
}