开发者

Best method for comparing windows directory names [duplicate]

开发者 https://www.devze.com 2023-01-05 22:14 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How can I compare (directory) paths in C#?
This question already has answers here: Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消