0
0
C Sharp (C#)programming~30 mins

Reading text files in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading text files
📖 Scenario: You are working on a simple program that reads a list of names from a text file and processes them.
🎯 Goal: Build a C# program that reads all lines from a text file called names.txt and prints each name to the console.
📋 What You'll Learn
Create a string array variable to hold the lines read from the file
Use a string variable to store the file path names.txt
Use System.IO.File.ReadAllLines to read the file
Use a foreach loop to print each name
💡 Why This Matters
🌍 Real World
Reading text files is common when working with data stored in files, like lists, logs, or configuration settings.
💼 Career
Many programming jobs require reading and processing files to handle data input, reports, or user information.
Progress0 / 4 steps
1
Create the file path variable
Create a string variable called filePath and set it to the exact value "names.txt".
C Sharp (C#)
Need a hint?

Use double quotes around the file name to create a string.

2
Read all lines from the file
Add a string array variable called names and set it to System.IO.File.ReadAllLines(filePath).
C Sharp (C#)
Need a hint?

Use System.IO.File.ReadAllLines with the filePath variable to read all lines.

3
Print each name using a foreach loop
Use a foreach loop with the variable name to iterate over names and print each name using Console.WriteLine(name).
C Sharp (C#)
Need a hint?

Use Console.WriteLine(name); inside the loop to print each name.

4
Run the program to display the names
Write Console.WriteLine statements inside the foreach loop to print each name from the names array. Run the program to see the output.
C Sharp (C#)
Need a hint?

Make sure the names.txt file contains these exact names, each on its own line:

Alice
Bob
Charlie
Diana
Ethan