Display File Contents - C# Programming Exercise

In this exercise of C#, you need to create a program that displays all the contents of a text file on the screen. The file name will either be entered via the command line, or if no file name is provided in the command line, the program should ask the user for it. To read the file's content, you must use the StreamReader class. The program should properly handle errors, such as checking if the file exists before attempting to read it.

This exercise is a great opportunity to learn about file handling in C#, specifically how to use the StreamReader class to read text from a file efficiently. It also allows you to practice user input handling and reading arguments from the command line. It’s a useful way to improve skills in working with input and output streams in C#.

 Category

File Management

 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

// 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
        }
    }
}

 Share this C# exercise

 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#.

  •  Extended TextToHTML (files)

    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...

  •  Logger

    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 ...

  •  More

    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...

  •  Text replacer

    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...

  •  Count letters in a file

    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...

  •  Reading a binary file (1: BMP)

    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 ...