Tom, Dick and Harry

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

Assignment One

This topic leads to:

Don't Cross the Streams

Summary

This exercise will introduce you to reading data from a text file. You will create a simple text file using Notepad or some other editor and then locate and load it using C# to print the contents out to the console.

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. Create a text document using Notepad or another text editor. Save it in a convenient location with a simple path. The text document should contain the following three lines.
    Tom, Jones, Singer
    Dick, Tracey, Investigator
    Harry, Wales, Pilot
  2. Now create a console program to create and open a StreamReader to this file and read each line, and then write it to the console.
  3. Now create a Person class, with three properties
    1. FirstName
    2. LastName
    3. JobTitle
  4. Modify the program to create an instance of this class for each line in the file, and initialise the properties of the object from the data from the file. Hint: Look up the Split method of the String class.
  5. Now make the program print out the values from the objects with a formatted string like "Tom Jones is a Singer".

Questions

  1. In stage 4 above, how many different approaches can you think of to do this? Did any of them involve using constructors on the Person class?
  2. Can you modify this program to allow you to enter details of more people, and then save that data back to the file in the correct format?