如何比较两个目录并获取丢失的文件? c#winform
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何比较两个目录并获取丢失的文件? c#winform相关的知识,希望对你有一定的参考价值。
这是代码:
enter code here
private void button1_Click(object sender, EventArgs e)
{
try
{
string[] Folder1 = Directory.GetFiles(txtFolder1.Text, comboBox1.SelectedItem.ToString());
string[] Folder1FileNames = new string[Folder1.Length];
int c = 0;
string fname1;
foreach (string f in Folder1)
{
fname1 = Path.GetFileName(f);
Folder1FileNames[c] = fname1;
c++;
}
string fname2;
string[] Folder2 = Directory.GetFiles(txtFolder2.Text, comboBox1.SelectedItem.ToString());
string[] Folder2FileNames = new string[Folder2.Length];
int t = 0;
foreach (string f in Folder2)
{
fname2 = Path.GetFileName(f);
Folder2FileNames[t] = fname2;
t++;
}
int m=0;
foreach (string f in Folder1FileNames)
{
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length)
{
m++;
if (m == Folder2FileNames.Length)
{
Label newlabe = new Label();
newlabe.Text = f;
if(!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
m = 0;
}
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
我创建了两个包含Files From SourceDirectory(Folder1)和CompareDirectory(Folder2)的数组,然后更多2个包含文件名的数组,不包括完整的ptah(为了比较araays),然后我试图比较数组,并将缺少的文件添加到列表框中。问题是当我尝试它时它给了我源文件夹中第一个丢失的文件,(例如源文件夹包含下一个文件:a.txt,b.txt,c.txt,d.txt和compare文件夹包含:a .txt,b.txt,列表框中的结果将是c.txt,标签将显示:“你是不在数组索引中”)我该怎么办?谢谢!
答案
您可以使用更简单,更整洁的解决方案,类似的应该可以工作:
var dir1Files = Directory
.EnumerateFiles(txtFolder1.Text, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName);
var dir2Files = Directory
.EnumerateFiles(txtFolder2.Text, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName);
var diffs = dir1Files.Except(dir2Files).Distinct().ToArray();
listBox1.Items.AddRange(diffs);
另一答案
谢谢你们,我成功地按照自己的方式去做了。多数民众赞成我的旧代码:
int m=0;
foreach (string f in Folder1FileNames)
{
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length)
{
m++;
if (m == Folder2FileNames.Length)
{
Label newlabe = new Label();
newlabe.Text = f;
if(!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
m = 0;
}
新的是:`
int m = 0;
foreach (string f in Folder1FileNames)
{
m = 0;
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length-1)
{
m++;
if (m == Folder2FileNames.Length-1)
{
if (Folder2FileNames[m] != f)
{
Label newlabe = new Label();
newlabe.Text = f;
if (!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
}
}
现在它运行良好,这样我就不会超出数组索引了
另一答案
// Find the set difference between the two folders.
// For this example we only check one way.
var queryList1Only = (from file in list1
select file).Except(list2, myFileCompare);
Console.WriteLine("The following files are in list1 but not list2:");
foreach (var v in queryList1Only)
{
Console.WriteLine(v.FullName);
}
以上是关于如何比较两个目录并获取丢失的文件? c#winform的主要内容,如果未能解决你的问题,请参考以下文章
如何用C语言实现,读取两个文件数据,然后比较两个数据,如果有不同,转换类型并输出???