Answer to Question #242793 in C# for Gayatri

Question #242793

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



Q2. Write a Code to perform File Copy operation. You need to accept the source and destination file names. The data should be copied from source file to destination file.

Handle all the exceptions that might occur during the file copy operation.


1
Expert's answer
2021-09-27T01:54:59-0400
Q1

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();
        }
    }
}

Q2. 


using System;
using System.Collections.Generic;
using System.IO;


namespace App
{


   
    class Program
    {
       
        static void Main(string[] args)
        {
            Console.Write("Enter the source file name: ");
            string sourceFile = Console.ReadLine();
            Console.Write("Enter the destination file name: ");
            string destinationFile = Console.ReadLine(); ;
            try
            {
                File.Copy(sourceFile, destinationFile, true);
            }
            catch (IOException iox)
            {
                Console.WriteLine(iox.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
APPROVED BY CLIENTS