25 December 2013

C# Program to Copy a File into Another File

This program will help C# developers to copy a gen file into another file using C# inbuilt function. There is a direct method to copy file File.Copy,  where you need to pass source and target files path.
Another method is get the fileinfo and the then call CopyTo method of fileinfo object. The code for both the methods are given below. Please comment if you face any problem.
using System;
using System.IO;
namespace MyApp
{
    class file_copy_class
    {
        public static void Main(string[] args)
            {
            string source_file = @"d:\source\test.txt";
            string target_file = @"d:\target\test.bak";
            //Method 1
            if (File.Exists(source_file))
            {
                File.Copy(source_file, target_file, true);
            }
            //Method 2
            if (File.Exists(source_file))
            {
                FileInfo objFile = new FileInfo(source_file);
                objFile.CopyTo(target_file, true);               
 
            }


                     Console.Read();
        }
    }
}

No comments:

Post a Comment