I have 2 DirectoryInfo
objects and want to check if they are pointing to the same directory. Besides comparing their Fullname, are there any other better ways to do this? Please disregard the case of links.
Here's what I have.
DirectoryInfo di1 = new DirectoryInfo(@"c:\temp");
DirectoryInfo di2 = new DirectoryInfo(@"C:\TEMP");
if (di1.FullName.ToUpperInvariant() == di2.FullName.ToUpperInvariant())
{ // they are the same
...
}
Thanks.
Under Linux you could compare the INode numbers of the two files wheather they are identical. But under Windows there is no such concept, at least not that I know off. You would need to use p/invoke to resolve the links if any.
Comparing strings is the best you can do. Note that using String.Compare(str1, str2, StringComparison.OrdinalIgnoreCase)
is faster than your approach of ToUpperInvariant()
as it doesn't allocate new strings on the heap and won't suffer problems inherent in using a linguistic text comparison algorithm to compare file paths.
You can use Uri objects instead. However, your Uri objects must point to a "file" inside these directories. That file doesn't actually have to exist.
private void CompareStrings()
{
string path1 = @"c:\test\rootpath";
string path2 = @"C:\TEST\..\TEST\ROOTPATH";
string path3 = @"C:\TeSt\RoOtPaTh\";
string file1 = Path.Combine(path1, "log.txt");
string file2 = Path.Combine(path2, "log.txt");
string file3 = Path.Combine(path3, "log.txt");
Uri u1 = new Uri(file1);
Uri u2 = new Uri(file2);
Uri u3 = new Uri(file3);
Trace.WriteLine(string.Format("u1 == u2 ? {0}", u1 == u2));
Trace.WriteLine(string.Format("u2 == u3 ? {0}", u2 == u3));
}
This will print out:
u1 == u2 ? True
u2 == u3 ? True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With