Answer to Question #189426 in C# for CHANDRASENA REDDY

Question #189426

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.


1
Expert's answer
2021-05-14T11:09:13-0400
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();
        }
    }
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS