C# - Copy Content of One File to Another, Overwrite Same File Name?

Learn how to copy the content of one file to another file by overwriting the file, if file has the same name using C# program?
Submitted by IncludeHelp, on November 02, 2017 [Last updated : March 26, 2023]

Given a file and we have to copy its content to another file by overwriting same file name using C# program.

To copy content of one file to another file by overwriting same file name in C#, we use File.Copy() method.

File.Copy()

This is a method of "File class, which is used to copy all data of source file to the destination file, here we are using an extra parameter to over write the file.

Syntax

File.Copy(source_file,dest_file,overWrting);

Parameter(s)

  1. source_file - From which we are copying data content.
  2. dest_file - In which data is being copied.
  3. overWrting - It is a Boolean flag, true allowed overwriting.

C# program to copy content of one file to another file by overwriting same file name

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      string data;

      Console.WriteLine("Content Before copy:\n");
      data = File.ReadAllText("source/ABC.TXT");
      Console.WriteLine("Content of source/ABC.TXT :\n" + data);

      data = File.ReadAllText("dest/ABC.TXT");
      Console.WriteLine("Content of dest/ABC.TXT :\n" + data + "\n\n\n");

      File.Copy("source/ABC.TXT", "dest/ABC.TXT", true);

      Console.WriteLine("Content After copy:\n");
      data = File.ReadAllText("source/ABC.TXT");
      Console.WriteLine("Content of source/ABC.TXT :\n" + data);

      data = File.ReadAllText("dest/ABC.TXT");
      Console.WriteLine("Content of dest/ABC.TXT :\n" + data);

    }
  }
}

Output

Content Before copy:

Content of source/ABC.TXT :
India is a great country.
Content of dest/ABC.TXT :
Think big, Think beyond.


Content After copy:

Content of source/ABC.TXT :
India is a great country.
Content of dest/ABC.TXT :
India is a great country.

Explanation

In the above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program.

Here program is copying the content of 'source/ABC.TXT' to 'dest/ABC.TXT' and In above Copy method there is a third Boolean parameter is used to allow/deny overwriting content in case of same file name.

C# File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.