如何处理目录我有2个Dir Test1和Test2 [英] How Do I Handle Dir I Have 2 Dir Test1 And Test2

查看:104
本文介绍了如何处理目录我有2个Dir Test1和Test2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个目录,test1和test2。 test1包含2个文件:abc.txt和xyz.txt,而在test2中有3个文件:abc.txt,sdf.txt和fgh.txt。

我只想将两个文件复制到另一个目录如

xyz.txt不在test2中,所以复制它并将其放在test2中。

同样使两个目录相同:不要触摸abc.txt因为它存在于两者中(虽然它们的包含不同)。

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).

推荐答案

它并不复杂:

将每个文件夹的内容列入字符串数组:Directory.GetFiles将这样做。

然后创建一个比较器,仅引用文件名,并使用Linq Except。

这是一个简单的事情使用File.Copy或File.Move自行移动文件:

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:
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)
    {

    }







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();
        }
    }



忘记比较器类...:O [/ edit]


[edit]Forgot the comparer class... :O [/edit]


这篇关于如何处理目录我有2个Dir Test1和Test2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆