Copying Files In C#

Copying Files in C#:
There are many ways in c# to copy files and many classes available which allow different operations on Files. The commonly used class in c# to copy files is FileInfo. FileInfo is defined in System.IO. The method used to copy files in FileInfo class is CopyTo().Now here is an example how to copy a file.
class Program
    {
        static void Main(string[] args)
        {
            FileInfo fi = new FileInfo(@"F:\Posts\Email Links.txt");
            fi.CopyTo(@"F:\Posts\new.txt");
          
        }
    }
Copying Folders and Files:
In above example we have created an object of FileInfo class and specified the file path we want to copy.Then we called CopyTo() method and specified the file path and name where we want to copy the file.In this example we have copied only one file if we want to copy all files in a Directory logic will be bit different.This example will show how to copy all files and folders present in a Directory to another Directory.This example uses recursion to copy files and folders.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleFile_Read
{
    class CopyDirectory
    {
        static void Main(string[] args)
        {
            CopyDirectory copdir = new CopyDirectory();
            copdir.Copy();
           
        }
        public void Copy()
        {
            DirectoryInfo diSource = new DirectoryInfo(@"F:\Posts");
            DirectoryInfo diTarget = new DirectoryInfo(@"G:\copydata");



            CopyAll(diSource, diTarget);
        }
        public void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {

            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }
            foreach (FileInfo fi in source.GetFiles())
            {

                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);

            }
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
               
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }


    }
}

In this example we have copied the Folder named “Posts” from the Directory “F:\” to “G:\Copydata”.All the files and folders within this folder will be copied.Here all files in the folder will be copied first and then folders will be copied.



Comments

Popular posts from this blog

Check if ViewBag is null or doesn't exist

Using Progress Bar In C#

Jquery serer side datatables in asp.net