如何在两个目录之间进行比较并获取丢失的文件?C#Winform [英] How to compare between two directories and get the missing files? 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;
}
我创建了两个包含SourceDirectory(Folder1)和CompareDirectory(Folder2)中的文件的数组,然后创建了两个包含文件名且没有完整ptah的数组(以便在araay之间进行比较),然后我尝试了比较数组,然后将丢失的文件添加到列表框中.问题是,当我尝试它时,它给了我源文件夹中第一个丢失的文件(例如,源文件夹包含下一个文件:a.txt,b.txt,c.txt,d.txt并比较文件夹包含:a.txt,b.txt,列表框中的结果将是c.txt,并且标签将显示:您不在数组索引中")我应该怎么办 ?谢谢!
I created two arrays that contains Files From SourceDirectory(Folder1) and CompareDirectory(Folder2) , then more 2 arrays that contains the files name with out the full ptah (in order to compare between the araays) ,then i have tried to compare between the arrays ,and add the missing file to the list box . the problem is that when I tried it it gave me the first missing file from the source folder , (e.g source folder contains the next files : a.txt,b.txt,c.txt,d.txt and compare folder contains:a.txt,b.txt , the result in the list box will be c.txt , and the label will show:"you are out of the array index" ) what should i do ? thanks!
推荐答案
您可以使用更简单,更整洁的解决方案,类似的方法应该可以解决:
You can go with a bit simpler and tidier solution, something like that should work:
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);
这篇关于如何在两个目录之间进行比较并获取丢失的文件?C#Winform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!