我正在尝试在path1中搜索文件。如果该文件存在于path2中,它将列在listView上。
这是我的代码。它似乎不起作用......
string path = @"C:\temp\code\path1";
string path2 = @"C:\temp\code\path2";
string fileType = "*.h";
DirectoryInfo d1 = new DirectoryInfo(path);
DirectoryInfo d2 = new DirectoryInfo(path2);
foreach (FileInfo f1 in d1.GetFiles(fileType, SearchOption.AllDirectories))
{
foreach (FileInfo f2 in d2.GetFiles(fileType, SearchOption.AllDirectories))
{
if (f1 == f2)
{
lstProjectFiles.Items.Add(f1.Name).SubItems.Add(path);
}
else
{
MessageBox.Show("False");
}
}
}
答案 0 :(得分:3)
比较f1 == f2
时,您将比较不同的FileInfo
个对象的引用。您需要比较文件及其子文件夹的名称(我正在删除文件夹名称的开头以仅保留公共部分):
if (f1.FullName.Replace(path, "") == f2.FullName.Replace(path2, ""))
此比较基于文件名及其在文件夹结构中的位置。
答案 1 :(得分:0)
您应该只使用FileInfo class的Name属性。 FileInfo类中还有其他有用的信息,但这不会告诉您文件包含相同的数据(不确定这是否是您尝试做的)。
string path = @"C:\temp\code\path1";
string path2 = @"C:\temp\code\path2";
string fileType = "*.h";
DirectoryInfo d1 = new DirectoryInfo(path);
DirectoryInfo d2 = new DirectoryInfo(path2);
foreach (FileInfo f1 in d1.GetFiles(fileType, SearchOption.AllDirectories))
{
foreach (FileInfo f2 in d2.GetFiles(fileType, SearchOption.AllDirectories))
{
if (f1.Name == f2.Name)
{
// you could also test the size before comparing actual data
if (f1.Length == f2.Length)
{
Console.WriteLine(string.Format("these files might be the same: {0}, {1}", f1.Name, f2.Name));
}
//lstProjectFiles.Items.Add(f1.Name).SubItems.Add(path);
}
else
{
Console.WriteLine("False");
}
}
}