1

When attempting to return all other files from the same directory that a specified file resides in, the files being returned are including the specified file. Lets assume I have three files out in a server share on my network:

  • \\Server\Share\Path\To\file1.ext
  • \\Server\Share\Path\To\file2.ext
  • \\Server\Share\Path\To\file3.ext

When I attempt to filter out file2 using the .Equals() method on the FileInfo object, the file is still being included.

FileInfo theFile = new FileInfo(@"\\Server\Share\Path\To\file2.ext");
List<FileInfo> allOtherFilesList = theFile.Directory.EnumerateFiles("*").Where(f => !f.Equals(vidFile)).ToList();

//Returned files:
\\Server\Share\Path\To\file1.ext
\\Server\Share\Path\To\file2.ext
\\Server\Share\Path\To\file3.ext

If I use the .Equals() method on the FileInfo.FullName property, I am returned a list of files as I would expect

FileInfo theFile = new FileInfo(@"\\Server\Share\Path\To\file2.ext");
List<FileInfo> allOtherFilesList = theFile.Directory.EnumerateFiles("*").Where(f => !f.FullName.Equals(vidFile.FullName)).ToList();

//Returned files:
\\Server\Share\Path\To\file1.ext
\\Server\Share\Path\To\file3.ext

Surely, there is some aspect of the .Equals() method that I'm not understanding? I would have thought that two FileInfo objects representing the same file would be the same.

  • 4
    Did you have time to check https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8 to see if `FileInfo` has `Equals` method? – Alexei Levenkov Mar 09 '20 at 05:51
  • 1
    @AlexeiLevenkov - The `.Equals()` method is a base method for the `object` type of which all .NET objects inherit from. – вʀaᴎᴅᴏƞ вєнᴎєƞ Mar 09 '20 at 05:55
  • 4
    @вʀaᴎᴅᴏƞвєнᴎєƞ That doesn't mean that classes override `Equals`. I think the base version just does a reference equals. – Zer0 Mar 09 '20 at 06:02
  • 1
    As @Zer0 mentioned, FileInfo does not override `Equals`. So the result is correct, these are two different objects, just pointing to the same file. – Yosh Mar 09 '20 at 08:15

0 Answers0