Reputation: 7
I have the following code which will return the filename of all files within my directory and sub-directories of documents. I would now want to compare files which have identical filenames and see if their size is the same. I am not sure on how I would be able to add duplicate file names to a class and to then compare the filesize of these.
Below is the code I have working so far
private static void ListAllDuplicateFiles()
{
string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
List<FileDetail> fileDetails = new List<FileDetail>();
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileDetail fileDetail = new FileDetail(fileInfo);
fileDetails.Add(fileDetail);
}
foreach (FileDetail fileDetail in fileDetails)
{
Console.WriteLine(fileDetail.Filename);
}
Console.ReadLine();
}
Upvotes: 0
Views: 49
Reputation: 258
You can create a list of string to store the names that are duplicate, then use the list of string to do the comparison that you want
private static void ListAllDuplicateFiles()
{
string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
List<string> duplicates = new List<string>();
List<FileDetail> fileDetails = new List<FileDetail>();
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileDetail fileDetail = new FileDetail(fileInfo);
fileDetails.Add(fileDetail);
if(fileDetails.Select(f=>f.Filename).Contains(file))
{
duplicates.Add(file);
}
}
foreach(string duplicate in duplicates)
{
//Do what you want with the list of duplicated file details
var duplicateFileDetails = fileDetails.Where(f=>f.Filename == duplicate).ToList();
}
foreach (FileDetail fileDetail in fileDetails)
{
Console.WriteLine(fileDetail.Filename);
}
Console.ReadLine();
}
Upvotes: 0