Possible Duplicate:
How can I compare (directory) paths in C#?
I have a filename and a directory name and I want to determent if the file is in the directory. My first thought was to use string comparison and check that the filena开发者_高级运维me string starts with the directory name string. However, that would fail in the case where the directory name was a UNC path and the filename was a mapped drive. Or if there were some other form of alias in one of the strings.
The string comparison just doesn't seem like a reliable method. Is there a built in .NET function for determining if 2 'DirectoryInfo' objects are pointing to the same folder?
You should use the Path class.
Something like the following would do the trick:
string.Compare(Path.GetDirectoryName(filePath), directoryPath.Trim('\\'), true)
If you wanted to handle relative paths then you can convert directoryPath and filePath into full paths first:
string.Compare(Path.GetDirectoryName(Path.GetFullPath(filePath)), GetFullPath(directoryPath).Trim('\\'), true)
EDIT: Edited to perform case invariant comparisons.
精彩评论