C# For Technical Writers: Programming Exercises

Week 3

  1. This problem has several parts that build on each other.
    1. First, you will need a text file to use as input. You can create your own, or use this one: names.txt.
    2. Write a program that reads every line in the file and prints only lines that contain the substring "er" (case sensitive).
      • Hint: Use the string.Contains method.
      • Note: I picked the substring "er" because it appears in the text file that I created (see link above). You can test for any substring that you like.
    3. Modify the program so that it prompts the user to enter the name of a file to open.
      • Hint: When you test your program, enter the full path. The StreamReader object expects either the full path, or a relative path from the application's current directory.
    4. Now add the following feature: Before opening the file, call the File.Exists method. The input to the method is the file name, and the output is a bool value. Do not open the file unless this method returns true. Optionally, if the method returns false, print an error message.
      • Hint: MSDN has some code examples that use File.Exists.

Here is some example output for this program:

Enter a file name:
> C:\Users\Bob\Documents\name.txt
Ella Fitzgerald
Ron Carter
Wayne Shorter
Herbie Hancock
Horace Silver
Art Pepper
Cannonball Adderley
Dexter Gordon
Oliver Nelson
Joe Henderson
Charlie Parker

Example #2:

Enter a file name:
> name.txt
No such file.

Email me if you get stuck!


Main Page