Wednesday, July 17, 2013

Copy folders and files - example using LINQ

Their are many examples available to copy entire content of a folder to another folder also retaining its file structure. Here I tried to do the same just with a different flavor. I used LINQ which is new and I haven't came across anyone who used it's power.

Concept is very simple with following steps:
  1. Get list of all files with complete path.
  2. Check each file and determine if corresponding folder structure exists? if not then create the folder.
  3. Copy the relevant file to destination location
Created simple console application for reference and use it as per your requirement.

namespace CopyFilesLINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            string src = @"D:\Adobe_Photoshop_CS3";
            string dest = @"d:\TestCopy";
            string DD;
            String[] saFiles = Directory.GetFiles(src, "*.*", SearchOption.AllDirectories);
            double dlen = saFiles.Length, dcnt = 0.00;
            foreach (var file in saFiles)
            {
                string[] x = ((from f in dest.Split(Path.DirectorySeparatorChar) 
                               select f).Union(from s in file.Split(Path.DirectorySeparatorChar) 
                                               where !src.Split(Path.DirectorySeparatorChar).Contains(s) 
                                               select s)).ToArray();
                for (int i = 0; i < (x.Length - 1); i++)
                {
                    if (i == 0)
                        DD = x[i];
                    else
                        DD = string.Format(@"{0}{1}{2}", DD, Path.DirectorySeparatorChar.ToString(), x[i]);
                    if (!Directory.Exists(DD))
                        Directory.CreateDirectory(DD);
                }
                try
                {
                    File.Copy(file, string.Join(Path.DirectorySeparatorChar.ToString(), x));
                }
                catch (Exception e)
                {
                    // record the exception in trace log or in a list to refer it later or display
                }
                dcnt++;
                
                Console.SetCursorPosition(1,0);
                Console.WriteLine(string.Format("Copy progress {0} %", ((dcnt / dlen) * 100).ToString("0.00")));
            }
            Console.SetCursorPosition(1, 0);
            Console.WriteLine("file Copy successful");
            Console.ReadLine();
        }
    }
}