Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to compare two filenames to see if they are the same file? [duplicate]

Possible Duplicate:
Best way to determine if two path reference to same file in C#

So I have two Windows filenames I need to compare to determine if they are the same. One the user gave me, one given to me by another program. So how should you compare:

C:\Program Files\Application1\APP.EXE
C:\Progra~1\Applic~1\APP.EXE
C:\program files\applic~1\app.exe

I can't seem to find a way to consistently 'normalize' the path, I tried using Path.GetFullPath(path) and new FileInfo(path).FullName and neither seem to resolve this.

UPDATE:

Path.GetFullPath(path) will correct the short to long name conversion but it will not normalize case. Thus a StringComparer.OrdinalIgnoreCase.Equals(path1, path2) is required.

like image 592
csharptest.net Avatar asked Nov 17 '09 18:11

csharptest.net


People also ask

How would you find out if two files are exactly the same?

Comparison Using diff GNU diff can compare two files line by line and report all the differences. The output indicates that file1 and file3 are the same, and file2 has different contents.

What is the best way to compare two files?

Use the diff command to compare text files. It can compare single files or the contents of directories. When the diff command is run on regular files, and when it compares text files in different directories, the diff command tells which lines must be changed in the files so that they match.

How can I tell if two files are the same in Windows 10?

Start Windiff.exe. On the File menu, click Compare Files. In the Select First File dialog box, locate and then click a file name for the first file in the comparison, and then click Open. In the Select Second File dialog box, locate and then click a file name for the second file in the comparison, and then click Open.


1 Answers

You will need Path.GetFullPath() + case insensitive string comparison.

Running the following code:

using System;
using System.IO;

class Test {
 static void Main ()
 {
  //string [] str = new string[] {@"c:\program files\vim\vim72", @"c:\progra~1\vim\vim72"};
  string [] str = new string[] {@"c:\program files\Refere~1\microsoft", @"c:\progra~1\Refere~1\microsoft"};
  foreach (string s in str) {
   // Call s = Environment.ExpandEnvironmentVariables (s) if needed.
   Console.WriteLine (Path.GetFullPath (s));
  }
 }
}

gives:

c:\program files\Reference Assemblies\microsoft
c:\Program Files\Reference Assemblies\microsoft
like image 97
Gonzalo Avatar answered Sep 17 '22 16:09

Gonzalo