Don't Cross the Streams

Line: Files Line
Medium Difficulty Files Learning Outcome One Learning Outcome Two Exercise
Type: Exercise
You should have completed:

Tom, Dick and Harry

This topic leads to:

Music Shop

Simple XML

Summary

This exercise will introduce you to reading data from a binary file. You will create a program that can read to and write from a

Note: This method of storing data in a text file is known as CSV or comma-separated values (a.k.a. comma delimited) and is still in common use.

Task

  1. Design and implement a class which has four properties, of types int, string, float and bool.
    You can choose the names.
  2. Add a method that accepts a StreamWriter parameter and writes the state of the object to that stream.
  3. Add a method that accepts a StreamReader parameter and can read the state of the object from that stream.
  4. Write a test program to
    1. Create a new instance of your class
    2. Set its values
    3. Open a binary file and save the state of the object to it
    4. Close the file
    5. Clear the object reference variable by setting it to null
    6. Open the file to read from it
    7. Create a new instance of your class and read the state out of the file.
    8. Close the file
  5. Make sure to include exception handling for the file access.
  6. Check that the data read in is correct.

Questions

  1. Experiment by changing the order in which variables are read from the stream when reading. Does it work?
  2. How would you use the same file to store data from instances of two different classes?