Tom, Dick and Harry
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
- 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
- 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.
- Now create a Person class, with three properties
- FirstName
- LastName
- JobTitle
- 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.
- Now make the program print out the values from the objects with a formatted string like "Tom Jones is a Singer".
Questions
- 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?
- 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?