Answer to Question #332025 in C# for Babar302

Question #332025

Create a program to Delete and copy a file in C#.


1
Expert's answer
2022-04-21T12:30:16-0400
using System;
using System.IO;

namespace delete_copy_file
{
    class Program
    {
        public static void Main(string[] args)
        {
            int chose;
            string fname1, fname2;
            Console.WriteLine("Select options:");
            Console.WriteLine("(1) - Delete file");
            Console.WriteLine("(2) - Copy file");
            Console.Write("Chose: ");
            chose = Convert.ToInt32(Console.ReadLine());
            
            if (chose == 1)
            {
                Console.Write("Enter filename to delete: ");
                fname1 = Console.ReadLine();
                if(File.Exists(fname1))
                   {
                       try
                    {
                        File.Delete(fname1);
                       }
                    catch (IOException e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                    finally 
                    {
                        Console.WriteLine("File '{0}' is deleted", fname1);
                    }
                }
                else Console.WriteLine("File '{0}' does not exist", fname1);
            }
            else if (chose == 2)
            {
                Console.Write("Enter filename to copy: ");
                fname1 = Console.ReadLine();
                Console.Write("Enter where to copy: ");
                fname2 = Console.ReadLine();
                if(File.Exists(fname1))
                   {
                       try
                    {
                        File.Copy(fname1, fname2, true);
                       }
                    catch (IOException e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                    finally
                    {
                        Console.WriteLine("File '{0}' is copyed to '{1}'", fname1, fname2);
                    }
                    
                }
                else Console.WriteLine("File '{0}' does not exist", fname1);                
            }
            
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

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