比较 Windows 目录名称的最佳方法

发布于 2024-09-08 17:55:19 字数 401 浏览 0 评论 0原文

可能的重复:
如何比较 C# 中的(目录)路径? < /p>

有一个文件名和一个目录名,我想确定该文件是否在该目录中。我的第一个想法是使用字符串比较并检查文件名字符串是否以目录名字符串开头。但是,如果目录名是 UNC 路径且文件名是映射驱动器,则该操作会失败。或者如果其中一个字符串中有某种其他形式的别名。

字符串比较似乎不是一个可靠的方法。是否有内置的 .NET 函数来确定 2 个“DirectoryInfo”对象是否指向同一个文件夹?

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 filename 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2024-09-15 17:55:19

您应该使用 Path 类。

像下面这样的东西就可以解决问题:

string.Compare(Path.GetDirectoryName(filePath), directoryPath.Trim('\\'), true)

如果您想处理相对路径,那么您可以首先将directoryPath和filePath转换为完整路径:

string.Compare(Path.GetDirectoryName(Path.GetFullPath(filePath)), GetFullPath(directoryPath).Trim('\\'), true)

编辑:编辑以执行大小写不变的比较。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文