Using FileStream to Copy a File

One advantage to the byte-oriented I/O used by FileStream is that you can use it on any type of fileā€”not just those that contain text. For example, the following program copies any type of file, including executable files. The names of the source and destination files are specified on the command line.


/* Copy a file one byte at a time.
To use this program, specify the name of the source
file and the destination file. For example, to copy a
file called FIRST.DAT to a file called SECOND.DAT, use
the following command line:
using System;
using System.IO;
namespace ConsoleApplication1
    class CopyFile
        static void Main(string[] args)
            int i;
            FileStream fin = null;
            FileStream fout = null;
            if (args.Length != 2)
                Console.WriteLine("Usage: CopyFile From To");
                // Open the files.
                fin = new FileStream(args[0], FileMode.Open);
                fout = new FileStream(args[1], FileMode.Create);
                // Copy the file.
                    i = fin.ReadByte();
                    if (i != -1) fout.WriteByte((byte)i);
                } while (i != -1);
            catch (IOException exc)
                Console.WriteLine("I/O Error:\n" + exc.Message);
                if (fin != null) fin.Close();
                if (fout != null) fout.Close();