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.
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();
}
}
}
Comments
Leave a comment