Exercise
Display File Contents
Objective
Create a program to display all the contents of a text file on screen (note: you must use a StreamReader). The name of the file will be entered in the command line or (if there is no command line present) asked to the user by the program.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for input/output handling
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
// Declaring a variable to store the file name
string fileName;
// Checking if a file name was provided as a command-line argument
if (args.Length > 0)
{
// Assigning the first argument as the file name
fileName = args[0];
}
else
{
// Asking the user to enter the file name if no argument was provided
Console.Write("Enter the file name: ");
fileName = Console.ReadLine();
}
// Trying to open and read the file contents
try
{
// Initializing a StreamReader to read the file's contents
using (StreamReader reader = new StreamReader(fileName))
{
// Reading all lines of the file and displaying them
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line); // Printing each line to the console
}
}
}
// Catching exceptions if the file cannot be opened or read
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found."); // Displaying error if file does not exist
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message); // Displaying any other errors
}
}
}
More C# Programming Exercises of File Management
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
In this exercise of C#, you need to expand the TextToHtml class so that it can dump its result to a text file. You should create a ToFile method that ta...
In this exercise of C#, you need to create a Logger class with a static Write method, which will append a certain text to a log file. The method should ...
In this exercise of C#, you need to create a program that behaves like the Unix "more" command. The program should display the contents of a text file and prom...
In this exercise of C#, you need to create a program to replace words in a text file, saving the result into a new file. The program should take as parameters the fil...
In this exercise of C#, you need to create a program to count how many times a specific character appears inside a file of any kind. The file and the letter to search...
In this exercise of C#, you need to create a program that checks if a BMP image file seems to be correct. The program must verify if the first two bytes of the file ...