Display file contents Learn programming C# Sharp

Lesson:

File Management


Exercise:

Display file contents 15


Objetive:

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.


Code:

using System;
using System.IO;
namespace Reader
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter name of file: ");
            string nameFile = Console.ReadLine();

            StreamReader myfile;
            try
            {
                myfile = File.OpenText(nameFile);
                string line = " ";
                do
                {
                    line = myfile.ReadLine();
                    if (line != null)
                    {
                        Console.WriteLine(line);
                    }
                }
                while (line != null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error al intentar abir el fichero.");
            }
            Console.ReadLine();
        }
    }
}