NullReferenceException NullReferenceException - 1 year ago 75
C# Question

Comparing files from different folders

I am trying to search files in path1. If that file exists in path2, it will be listed on a listView.

Here is my code. It doesn't seem to work...

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)

Answer Source

When you compare f1 == f2, you're comparing references of FileInfo objects which will be different. You need to compare the names of the files and their subfolders (I'm removing the beginning of the folder name to leave the common part only):

if (f1.FullName.Replace(path, "") == f2.FullName.Replace(path2, ""))

This comparison is based on file name and it's location in the folder structure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download