Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
A variant of the file copy program


Here is a solution:

using System;
using System.IO;

public class CopyApp {

  public static void Main(string[] args) {
    FileCopy(args[0]);
  }
 
  public static void FileCopy(string fromFile){
      try
      {
          using (Stream fromStream = new FileStream(fromFile, FileMode.Open))
          {
              long strmLgt = fromStream.Length;
              byte[] strmContent = new byte[strmLgt];          // A byte array large enough to 
                                                               // hold the fromFile.

              int totalBytesRead = 0,
                  bytesRead,
                  n = 0;

              const int chuckSize = 100; 

              do{
                bytesRead = fromStream.Read(strmContent, totalBytesRead, Math.Min(chuckSize, (int)strmLgt - totalBytesRead));   
                totalBytesRead += bytesRead;
                n++; 
              } while (totalBytesRead < strmLgt && bytesRead > 0);

              foreach(byte bt in strmContent) Console.Write((char)bt);

              Console.WriteLine();
              Console.WriteLine("Number of calls to Read: {0}", n);
          }
      }
      catch (FileNotFoundException e)
      {
          Console.WriteLine("File {0} not found: ", e.FileName);
          throw;
      }
      catch (Exception)
      {
          Console.WriteLine("Other file copy exception");
          throw;
      }
 }

}

In the solution above we allocate a byte array, which is large enough to hold the entire fromFile. In the do-while loop we repeatedly read chunks of chunkSize (100) bytes. After outputting the bytes in strmContent to standard output we report the number of calls to Read.