C# Program to Copy a File


Introduction

C# is a high-level language that caters to the large needs of programmers. It can also help in copying a file. So, in this article, we will learn a C# Program to Copy a File. As we know file copying falls in the category of file handling. So, before we proceed further let us recap the definition of file handling.

File handling or file management in layman’s terms the various processes such as making the file, reading from it, writing to it, appending it, and so on. The reading and writing of files are the two most common operations in file handling.

The Need to Copy and the Method to Copy the File

Copying of a file is one of the very biggest assets in the computer. Various languages offer this and C# does this too. Many times the user wants to create a new file which has the same data from one of the old files and then add something to it. It will take a lot of time if the user first writes the old data and then add something. Why do this much when the user can simply copy the existing file data into a new file and then add something? So copying a file is a real deal in these tough situations. The file can be copied from the terminal. For copying the file Copy(String, String) is used.

Copy(String, String)

This method is used to copy an existing file into a new file. The complete file data is copied to the new file. Following is the syntax of the copy(string, string).

public static void Copy (string sourceFileName, string destFileName); 

This method prohibits the user to overwrite a file of the same name. Here two strings are the parameters. The first string gets the source file name which is the file to be copied. The second string is the destination file name. The file name in which the source file data is to be copied. As there is a constraint that this destination file name should neither be a directory nor an existing file.

This method does throw more than a couple of exceptions. Like UnauthorizedAccessException which occurs when the user’s code does not have the required permissions to access. When the source file name or the destination file name contains one or more invalid characters, has only white space, or the address specifies the directory then that exception is termed an ArgumentException. ArgumentNullException happens when the source file name or the destination file name is null.

Another one DirectoryNotFoundException happens when the location provided in either sourceFileName or destFileName is incorrect.

PathTooLongException happens when the given path, file name, or both surpass the maximum length set by the system.

If the source file is not found then FileNotFoundException is thrown. Now as we know this method prohibits the user to overwrite a file of the same name. So, when the user tries to do so IOException is thrown as a destination file exists or for any I/O error too. One more exception NotSupportedException is thrown when the source file name or the destination file name is in an invalid format

Now let us discuss the algorithm

Algorithm

By using this algorithm we can copy the source file to the destination file. File.Copy() method is being used

Step 1  Declaring string variable to store the address of the files.

Step 2  Using the File.Copy() to copy the contents from the existing file to the new file.

Step 3 −  A code line for catching the exception is thrown.

Step 4  A success message after the copying of the file is done.

Example

// A C# program for copying a file
//File.Copy() is used to copy the source file to the destination file
using System;
using System.IO;
using System.Text;
using System.Linq;
class ttpt {

   public static void Main() {
      // Address of both the files
      string OriginalFile = @"D:\source.txt";
      string FinalFile = @"D:\final.txt";
      try {
         // Method used to copy an existing file into a new file.
         File.Copy(OriginalFile, FinalFile);
      }
      catch (IOException iox) {
         // Exception message catching box
         Console.WriteLine(iox.Message);
      }
      Console.WriteLine("Copying of contents from source to destination file is completed") ;
   }
}

Output

Copying of contents from source to destination file is completed 

Now if the user overloads the syntax of File.Copy() with the third parameter which is a boolean parameter if true or false. Then this method gets the power to overwrite the file if the destination filename already exists.

Overloading File.Copy(String, String, Boolean)

This method is used to copy an existing file into a new file. The complete file data is copied to a new file. Following is the syntax of the copy(string, string, bool overwrite).

public static void Copy (string sourceFileName, string destFileName, bool overwrite); 

Here after overloading with true this method allows the user to overwrite a file of the same name.

This method does throw more than a couple of exceptions. Like UnauthorizedAccessException which occurs when the user’s code does not have the required permissions to access. When the source file name or the destination file name contains one or more invalid characters, has only white space, or the address specifies the directory then that exception is termed an ArgumentException. ArgumentNullException happens when the source file name or the destination file name is null.

Another one DirectoryNotFoundException happens when the location provided in either sourceFileName or destFileName is incorrect.

PathTooLongException happens when the given path, file name, or both surpass the maximum length set by the system.

If the source file is not found then FileNotFoundException is thrown.

This will throw IOException only when an IO error occurs or the overwritten part of overload is false and the destination file already exists.

Now let us discuss the algorithm

Algorithm

By using this algorithm we can copy the source file to the destination file. File.Copy() method is being used.

Step 1 − Declaring string variable to store the address of the files.

Step 2  Using the File.Copy() is overloaded with true to copy the contents from the existing file to the new file.

Step 3  A code line for catching the exception if thrown.

Step 4  A success message after the copying of the file is done.

Example

// A C# program for copying a file
//File.Copy() is used to copy the source file to the destination file
using System;
using System.IO;
using System.Text;
using System.Linq;
class ttpt {

   public static void Main() {
      // Address of both the files
      string OriginalFile = @"D:\source.txt";
      string FinalFile = @"D:\final.txt";
      try {
         // Method used to copy an existing file into a new file.
         
         // By this if final already exists then it will be overwritten
         File.Copy(OriginalFile, FinalFile, true);
      }
      catch (IOException iox){
         // Exception message catching box 
         Console.WriteLine(iox.Message);
      }
      Console.WriteLine("Copying of contents from source to destination file is completed") ;
   }
}

Output

Copying of contents from source to destination file is completed 

Conclusion

So, with this we come to the end of the article. In this article, we have discussed a c# program to copy a file. We have used File.Copy() in both ways as normal and overloaded. We discuss their syntax, exceptions and their algorithms. Then we saw the codes and with this, we end the article.

We hope this article enhances your knowledge of C#.

Updated on: 21-Apr-2023

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements