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.
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
a short test run says that the below code will work for the paths given:
bool CompareFileName(string file1, string file2)
{
var directory1 = Path.GetDirectoryName(file1);
var directory2 = Path.GetDirectoryName(file2);
var fileName1 = Path.GetFileName(file1);
var fileName2 = Path.GetFileName(file2);
return directory1.Equals(directory2, StringComparison.InvariantCultureIgnoreCase) &&
fileName1.Equals(fileName2, StringComparison.InvariantCultureIgnoreCase);
}
this assumes windows platform (an assumption made due to the windows centric paths given as example paths)
I use the FileInfo object. If you create a fileinfo object of a file that actually exists the Directory property gives a nicely formatted path name.
You also get the additional benefit of being able to test if the file actually exists.
精彩评论