C# - How to Copy Content of One File to Another File?

Learn, how to copy content of one file to another file 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 using C# program.

To copy content of one file to another file 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.

Syntax

File.Copy(source_file,dest_file);

Parameter(s)

  1. source_file - From which we are copying data content.
  2. dest_file - In which data is being copied.

C# program to copy content of one file to another file

using System;
using System.IO;

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

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

            File.Copy("ABC.TXT", "XYZ.TXT");

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

        }
    }
}

Output

Content of ABC.TXT :
India is a great country.
Content of XYZ.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.

In above function, overwriting a file with the same name is not allowed.

C# File Handling Programs »

Comments and Discussions!

Load comments ↻





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