Write a Code to Read and Display the contents of a text file. Accept the name of the file from the user. Handle all the exceptions that might occur during reading.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
using System.IO;
namespace C_SHARP
{
class Program
{
static void Main()
{
try{
//accept the name of the file from the user.
Console.Write("Enter the file name: ");
string textFile = Console.ReadLine();
using (StreamReader file = new StreamReader(textFile))
{
string line;
//read a line from the file
while ((line = file.ReadLine()) != null)
{
//display the line
Console.WriteLine(line);
}
//close the file
file.Close();
}
}
catch (Exception ex)
{
// Handle all the exceptions that might occur during reading.
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Comments
Leave a comment