Programming Course in C# ¡Free!

Display file contents

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

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.

Output



Solution


using System;
using System.IO;

class DisplayFileContent
{
static void Main()
{
Console.Write("Enter name of file: ");
string name = Console.ReadLine();


try 
{ 
StreamReader file; = File.OpenText(name);
string line=" ";

do
{
line = file.ReadLine();
if (line != null) 
{
Console.WriteLine(line);
}
}
while (line != null);
}
catch (Exception e) 
{
Console.WriteLine("Error!!!");
}
}
}