Answers to Chapter 22 Review Questions


Chapter 22


What is the main reason for using files?


Files provide permanent means for storing data.


How are streams represented in C# and .NET?


With objects of stream classes found in the System.IO namespace.


In what context have you already used streams in previous chapters?


Console.WriteLine and Console.ReadLine.


In which direction is the data moving when we talk about input from the program to a destination device or from a destination device to the program?


From a destination device to the program.


In what ways are text files and binary files similar? In what ways are they different?


They both consist of bits and bytes. The bits and bytes in text files are encoded into a list of characters. This is not the case for binary files.


Can you read a text file with a binary stream?




Suppose that you need to call just a single method only once in your program to manipulate a particular file in your file system. Which class would you use File or FileInfo (given that the method exists in both classes)? Why?


The File class contains static methods, so there is, as opposed to the FileInfo class, no need to first instantiate a File object before calling its methods. Because only a single call is needed, exactly one expensive security check is required whether we use FileInfo or File. So overall, File is the preferred class.


Suppose that you need to call several methods one after the other to manipulate one particular file in your file system. Which class would you use File or FileInfo (given that the methods exist in both classes)?


FileInfo is preferred, because it only requires one security check when objects of this class are instantiated. In contrast, File requires a security check for every method call.


Consider the following two lines:

 FileInfo newFile = new FileInfo(@"C:\MyTestFiles\HorrorStory.txt"); Console.WriteLine("Length of file: { 0} ", newFile.Length); 

What will happen in the second line if C:\MyTestFiles\HorrorStory.txt does not already exist?


The runtime will generate a System.IO.FileNotFoundException.


Briefly explain the difference between a file's full name and a file's relative name.


A file's full name includes the complete path to the file, from the root directory (A, B, C, and so on) through sub-directories to the short name of the file (Example: C:\MyFiles\TextFiles\MyHorrorStory.txt). A file's relative name does not contain the path (Example: MyHorrorStory.txt).


If a C# program ends normally, any unclosed files are automatically closed. Why then bother closing a file with the Close method?


If the program crashes, the program cannot automatically close the file, leaving it exposed to possible damage.


How do you know that the ReadLine method of the StreamReader class has reached the end of the corresponding file?


It returns null when the end of the file is reached.


Give another term for connecting a file to a stream.


Opening a file.


What does the OpenWrite and OpenRead methods of the FileInfo class return?


A FileStream object.

Answers to Chapter 22 Programming Exercises


Create a text file with Notepad called C:\MyTestFiles\ShortStory.txt with the contents:

 This text Only contains Three lines 

Write a program that tells the user the full name of the file and when it was created.

Please keep this program handy for exercise 2.


Extend the program in exercise 1 so that the program also counts the number of lines in C:\MyTestFiles\ShortStory.txt and shows this number on the console.


Exercises 1 and 2:

 using System; using System.IO; class FileInspector {     public static void Main()     {          //Exercise 2         string textLine;         StreamReader inStream;         int counter = 0;         try         {              //Exercise 1             FileInfo txtFile = new FileInfo(@"C:\MyTestFiles\ShortStory.txt");             Console.WriteLine("File name: " + txtFile.FullName);             Console.WriteLine("Creation time: " + txtFile.CreationTime);              //Exercise 2             inStream = txtFile.OpenText();             textLine = inStream.ReadLine();             while(textLine != null)             {                 counter++;                 textLine = inStream.ReadLine();             }             Console.WriteLine("Number of lines in text: {0}", counter);         }         catch (IOException exObj)         {             Console.WriteLine(exObj);         }     } } 

Write a program that contains an array called rainfall, containing twelve elements of type byte. Each element represents a monthly rainfall reading and can have a value between 0 and 200. Include a simple user interface so that the user can view the element values of rainfall and assign values to any one of its elements.

Expand the user menu so that the user can choose to save the contents of rainfall to a file called C:\MyTestFiles\Rainfall.dat. Furthermore, include an option in the user menu that allows the user to load the data contained in C:\MyTestFiles\Rainfall.dat back into the rainfall array. This must permit the user to save the rainfall data kept in the rainfall array, end the program, and later restart the program and load the Rainfall.dat data back into the rainfall array of the program.


Exercise 3:

 using System; using System.IO; class Rainfall {     private static byte [] rainfall = new byte [12];     private static FileStream outStream = null;     private static FileStream inStream = null;     public static void Main()     {         string answer;         int index;         byte rainfallReading;         Console.WriteLine("Choose between the following options: ");         Console.WriteLine("I)nput a rainfall reading");         Console.WriteLine("L)ist the rainfall readings");         Console.WriteLine("S)ave the rainfall readings");         Console.WriteLine("R)ead the rainfall readings from file");         Console.WriteLine("T)erminate program");         do         {             Console.Write("\nEnter choice: ");             answer = Console.ReadLine().ToUpper();             switch (answer)             {                 case "I":                     Console.Write("Enter month (1-12): ");                     index = Convert.ToInt32(Console.ReadLine());                     Console.Write("Enter rainfall reading: ");                     rainfallReading = Convert.ToByte(Console.ReadLine());                     rainfall[index - 1] = rainfallReading;                 break;                 case "L":                     Console.WriteLine("Rainfall readings:");                     foreach(int temp in rainfall)                     {                         Console.Write("{0} ", temp);                     }                     Console.WriteLine();                 break;                 case "T":                     Console.WriteLine("Bye bye");                 break;                 case "S":                     try                     {                         Console.WriteLine("Saving rainfall data to Rainfall.dat");                         FileInfo byteOutFile = new FileInfo (@"C: graphics/ccc.gif\MyTestFiles\Rainfall.dat");                         outStream = byteOutFile.OpenWrite();                         for(int i = 0; i < 12; i++)                         {                             outStream.WriteByte(rainfall[i]);                         }                     }                     catch (IOException exObj)                     {                         Console.WriteLine(exObj);                     }                     finally                     {                         outStream.Close();                     }                 break;                 case "R":                     try                     {                         Console.WriteLine("Reading data from Rainfall.dat");                         FileInfo byteInFile = new FileInfo (@"C: graphics/ccc.gif\MyTestFiles\Rainfall.dat");                         inStream = byteInFile.OpenRead();                         for (int i = 0; i < inStream.Length; i++)                         {                             rainfall[i] = (byte)inStream.ReadByte();                         }                         inStream.Close();                     }                     catch (IOException exObj)                     {                         Console.WriteLine(exObj);                     }                     finally                     {                         inStream.Close();                     }                 break;                 default:                     Console.WriteLine("Invalid choice. Try again");                 break;             }         }  while(answer != "T");     } } 


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: