Michel Keijzers
Michel Keijzers

Reputation: 15357

Check if two file names reference to the same file

Is there a way in C# (4.0) to check if two file names reference to the same file, preferably without opening them?

I.e. d:\x.txt should be equal to x.txt or ../x.txt if the the relative path points to d.

Upvotes: 2

Views: 2154

Answers (3)

ChrisF
ChrisF

Reputation: 137138

If you use Path.GetFullPath on both names they should resolve to the same string:

string fullPath1 = Path.GetFullPath(absolutePath);
string fullPath2 = Path.GetFullPath(relativePath);

Then fullPath1 should equal fullPath2 if they reference the same file. Make sure that you do a case insensitive comparison as Windows filenames are case insensitive.

Upvotes: 7

user280831
user280831

Reputation: 21

Yes, use Path.GetFullPath and then a case-insensitive compare:

var file1 = Path.GetFullPath(@"C:\TEMP\A.TXT");
var file2 = Path.GetFullPath(@"a.txt"); // Assuming current directory is C:\TEMP

// Test 1 (good)
if (file1.Equals(file2, StringComparison.OrdinalIgnoreCase))
{
   Console.WriteLine("Test 1: they match");
}

// Test 2 (fails when file paths differ by case)
if (file1 == file2)
{
    Console.WriteLine("Test 2: they match");
}

Most people run .NET on case-insensitive filesystems, so comparing paths that differ only by case using the == operator will not produce the desired result.

Upvotes: 2

Simon Whitehead
Simon Whitehead

Reputation: 65079

Perhaps this works for you?

FileInfo file1 = new FileInfo(@"D:\x.txt");
FileInfo file2 = new FileInfo(@"..\x.txt");

if (file1.FullName == file2.FullName) {
    // yes, they match..

Upvotes: 5

Related Questions