Click here to Skip to main content
15,883,829 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 directories, test1 and test2. test1 contains 2 files: abc.txt and xyz.txt, while in test2 there are 3 files: abc.txt, sdf.txt and fgh.txt.
I just want two copy the files in to another directory like
xyz.txt is not in test2 so copy it and place it in test2.
Likewise make both the directories the same: do not touch the abc.txt because it present in both (although their contains are different).
Posted
Updated 27-May-14 2:02am
v2

1 solution

It's not complex:
List the content of each folder into an array of strings: Directory.GetFiles will do that.
Then create a comparer to only reference the file names, and use Linq Except.
It's then a simple matter to use File.Copy or File.Move to shift the files themselves:
C#
string[] dir1 = Directory.GetFiles(@"D:\Temp\Dir1");
string[] dir2 = Directory.GetFiles(@"D:\Temp\Dir2");
var newFiles = dir1.Except(dir2, new FileNameComparer());
foreach (string s in newFiles)
    {

    }


C#
private class FileNameComparer : IEqualityComparer<string>
    {
    public bool Equals(string x, string y)
        {
        return Path.GetFileName(x) == Path.GetFileName(y);
        }

    public int GetHashCode(string obj)
        {
        return Path.GetFileName(obj).GetHashCode();
        }
    }

[edit]Forgot the comparer class... :O [/edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900