4

I need to copy all the files from one folder (Source) to another folder (Destination). I also need to to compare the two folders and increment a counter that stops at 100 if the content of the two folders are exact match with names only.

I do not need to compare the size of each file, just the names.

This is what I have tried but I am not getting the desire result as described above.

I am referencing some of the resources here: http://msdn.microsoft.com/en-us/library/bb546137.aspx

class Program
{
    class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
    {
        public FileCompare() { }

        public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
        {
            return (f1.Name == f2.Name &&
                    f1.Length == f2.Length);
        }
        public int GetHashCode(System.IO.FileInfo fi)
        {
            string s = String.Format("{0}{1}", fi.Name, fi.Length);
            return s.GetHashCode();
        }
    }

    static void Main(string[] args)
    {

        int i = 1;

        string sourcePath = @"C:\Users\Administrator\Desktop\Source";
        string destinationPath = @"C:\Users\Administrator\Desktop\Dest";

        string fileName = System.IO.Path.GetFileName(sourcePath);

        string source = System.IO.Path.Combine(sourcePath, fileName);
        string destination = System.IO.Path.Combine(destinationPath, fileName);

        System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(sourcePath);
        System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(destinationPath);

        IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*",
        System.IO.SearchOption.AllDirectories);

        IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*",
        System.IO.SearchOption.AllDirectories);


        string[] files = System.IO.Directory.GetFiles(sourcePath);

        foreach (string s in files)
        {
            fileName = System.IO.Path.GetFileName(s);
            destination = System.IO.Path.Combine(destinationPath, fileName);
            System.IO.File.Copy(s, destination, true);

            FileCompare myFileCompare = new FileCompare();
            bool areIdentical = list1.SequenceEqual(list2, myFileCompare);

            while (areIdentical != true)
            {
                Console.WriteLine(i++);
            }

        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
Asynchronous
  • 3,917
  • 19
  • 62
  • 96
  • Oh so close. "but I am not getting the desire result as described above" -- but what result _are_ you getting, and how does this differ from what you wanted, _specifically_? – Peter Duniho Dec 07 '14 at 01:07
  • I am not sure I am close. :) The increment is not working and I am having trouble with the Boolean evaluation using the while loop. When I run the above code, I get an endless loop, it appears as if the comparison part isn't working. – Asynchronous Dec 07 '14 at 01:09
  • I just meant that the question was presented "so close" to perfectly (which is rare here on SO). But it is missing some specifics; you can assist people in providing good answers if you would provide those details. Please detail _specifically_ what's happening and how that's different from what you wanted to happen. – Peter Duniho Dec 07 '14 at 01:11
  • It's also a little odd that you are setting `source` and `destination` to `C:\Users\Administrator\Desktop\Source\Source` and `C:\Users\Administrator\Desktop\Dest\Source`, respectively. But I suppose that's nothing to do with the algorithm itself. Note that the goal is not clear either; do you want to stop as soon as the directories have exactly the same content, or only after 100 files have been copied? Do you actually want to increment the counter for each file copied? Or something else? – Peter Duniho Dec 07 '14 at 01:13
  • Do you want to stop as soon as the directories have exactly the same content? Yes, not after 100 hundred files. Do you actually want to increment the counter for each file copied? Well, this makes more since, so yes. This way the counter will stop when the loop is done and all files are copied?? However, the bool will only evaluate to true when the content matches. Thank you again. – Asynchronous Dec 07 '14 at 01:24
  • What do you want to happen if the destination already has all of the files that would be copied? Should you stop immediately? What if the destination has _additional_ files? Are you comparing only the files from the source directory, or do extra files in the destination mean that you won't stop until you get to 100 files from the source directory have been copied? – Peter Duniho Dec 07 '14 at 01:27
  • The destination wont have 100 files, I simply used that number as an example: But yes When the destination has all the files from the source, then the loop will exit immediately and the counter, as you have suggested would have reached the total files and stopped. If the destination has all the files, then it will be overwritten. But the bool will evaluate depending on the match of the two folder. So if all the files are copied and for some reason they do not match, then the bool is false. – Asynchronous Dec 07 '14 at 01:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66339/discussion-between-unaverage-guy-and-peter-duniho). – Asynchronous Dec 07 '14 at 01:41
  • possible duplicate of [BackgroundWorker & Progressbar Issues c# Visual Studio 2010](http://stackoverflow.com/questions/13802258/backgroundworker-progressbar-issues-c-sharp-visual-studio-2010) – Peter Duniho Dec 07 '14 at 02:32

2 Answers2

10

You can try this solution, synchronize both directories.

class Program
{
    class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
    {
        public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
        {
            return (f1.Name == f2.Name);
        }
        public int GetHashCode(System.IO.FileInfo fi)
        {
            string s = fi.Name;
            return s.GetHashCode();
        }
    }

    static void Main(string[] args)
    {
        string sourcePath = @"C:\Users\Administrator\Desktop\Source";
        string destinationPath = @"C:\Users\Administrator\Desktop\Dest";

        System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(sourcePath);
        System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(destinationPath);

        IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*",
        System.IO.SearchOption.AllDirectories);

        IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*",
        System.IO.SearchOption.AllDirectories);

        bool IsInDestination = false;
        bool IsInSource = false;

        foreach (System.IO.FileInfo s in list1)
        {
            IsInDestination = true;

            foreach (System.IO.FileInfo s2 in list2)
            {
                if (s.Name == s2.Name)
                {
                    IsInDestination = true;
                    break;
                }
                else
                {
                    IsInDestination = false;
                }
            }

            if (!IsInDestination)
            {
                System.IO.File.Copy(s.FullName, System.IO.Path.Combine(destinationPath, s.Name), true);
            }
        }

        list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

        list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

        bool areIdentical = list1.SequenceEqual(list2, new FileCompare());

        if (!areIdentical)
        {
            foreach (System.IO.FileInfo s in list2)
            {
                IsInSource = true;

                foreach (System.IO.FileInfo s2 in list1)
                {
                    if (s.Name == s2.Name)
                    {
                        IsInSource = true;
                        break;
                    }
                    else
                    {
                        IsInSource = false;
                    }
                }

                if (!IsInSource)
                {
                    System.IO.File.Copy(s.FullName, System.IO.Path.Combine(sourcePath, s.Name), true);
                }
            }
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
mgigirey
  • 1,027
  • 9
  • 13
0

For a copy, each and everything from source to destination even any particular file missing in the destination then it will copy. you need to modify your index in remove

//if (s.FullName.Remove(0, 24) == s2.FullName.Remove(0, 24))
//my path is D:\TestProgram\ which contain two folders Prod_bin and Jul-2020
//so I have trim for if there are two files present on two locations so it will compare //name as well as the file location.

//file name D:\TestProgram\Prod_BIN\ABC\bin\sanyog.css
//D:\TestProgram\JUl-2020\ABC\bin\sanyog.css

//after remove it will be like ABC\bin\sanyog.exe.

//need to verify the index and try to implement it.

// and also need to replace your source and destination folder name like 
// mine string destfilePath = s.FullName.Replace("Prod_BIN", "JUL-2020");


    class Program
    {
        class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileSystemInfo>
        {
            public bool Equals(System.IO.FileSystemInfo f1, System.IO.FileSystemInfo f2)
            {
                return (f1.Name == f2.Name);
            }
            public int GetHashCode(System.IO.FileSystemInfo fi)
            {
                string s = fi.Name;
                return s.GetHashCode();
            }
        }

        static void Main(string[] args)
        {

            int i = 0;

            string sourcePath = @"D:\TestProgram\Prod_BIN";
            string destinationPath = @"D:\TestProgram\JUL-2020";

            System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(sourcePath);
            System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(destinationPath);

            IEnumerable<System.IO.FileSystemInfo> list1 = dir1.GetFileSystemInfos("*.*",
            System.IO.SearchOption.AllDirectories);

            IEnumerable<System.IO.FileSystemInfo> list2 = dir2.GetFileSystemInfos("*.*",
            System.IO.SearchOption.AllDirectories);

            bool IsInDestination = false;

            foreach (System.IO.FileSystemInfo s in list1)
            {
                IsInDestination = true;

                foreach (System.IO.FileSystemInfo s2 in list2)
                {
                    if (s.Name == s2.Name)
                    {
                        if (s.FullName.Remove(0, 24) == s2.FullName.Remove(0, 24))
                        {
                            IsInDestination = true;
                            break;
                        }
                    }
                    else
                    {
                        IsInDestination = false;
                    }
                }
                string destfilePath = s.FullName.Replace("Prod_BIN", "JUL-2020");
                if (!IsInDestination)
                {
                    i = i + 1;
                    if (s.Attributes.Equals(System.IO.FileAttributes.Directory))
                    {
                        Directory.CreateDirectory(destfilePath);
                    }
                    else
                    {
                        if (!s.Attributes.Equals(System.IO.FileAttributes.Hidden | System.IO.FileAttributes.Directory))
                            System.IO.File.Copy(s.FullName, System.IO.Path.Combine(Directory.GetParent(destfilePath).FullName, s.Name), true);
                    }
                }
            }
            Console.WriteLine("Total copied files : {0} Press any key to exit.", i);
            Console.ReadKey();

        }
    }
General Grievance
  • 4,555
  • 31
  • 31
  • 45