在 C# 中确定两个路径是否引用同一文件的最佳方法

问题描述:

在即将到来的 Java7 中,有一个 新 API 来检查两个文件对象是否是相同的文件引用.

In the upcoming Java7, there is a new API to check if two file object are same file reference.

.NET 框架中是否提供了类似的 API?

Are there similar API provided in the .NET framework?

我已经在 MSDN 上搜索过,但没有任何启发.

I've search it over MSDN but nothing enlighten me.

我希望它简单,但我不想按文件名进行比较,这会导致硬/符号链接和路径样式不同的问题.(例如 \\?\C:\C:\).

I want it simple but I don't want to compare by filename which will cause problems with hard/symbolic links and different style of path. (e.g. \\?\C:\, C:\).

我要做的只是防止重复的文件被拖放到我的链接列表中.

What I going to do is just prevent duplicated file being drag and dropped to my linklist.

据我所知 (1) (2) (3) (4),方式JDK7 是通过调用 GetFileInformationByHandle 在文件并比较 dwVolumeSerialNumber、nFileIndexHigh 和 nFileIndexLow.

As far as I can see (1) (2) (3) (4), the way JDK7 does it, is by calling GetFileInformationByHandle on the files and comparing dwVolumeSerialNumber, nFileIndexHigh and nFileIndexLow.

每个 MSDN:

您可以比较 BY_HANDLE_FILE_INFORMATION 结构中返回的 VolumeSerialNumber 和 FileIndex 成员,以确定两个路径是否映射到同一目标;例如,您可以比较两个文件路径并确定它们是否映射到同一目录.

You can compare the VolumeSerialNumber and FileIndex members returned in the BY_HANDLE_FILE_INFORMATION structure to determine if two paths map to the same target; for example, you can compare two file paths and determine if they map to the same directory.

我不认为这个函数是由 .NET 包装的,所以你必须使用 P/调用.

I do not think this function is wrapped by .NET, so you will have to use P/Invoke.

它可能适用于网络文件,也可能不适用于网络文件.根据 MSDN:

It might or might not work for network files. According to MSDN:

根据操作系统的底层网络组件和连接的服务器类型,GetFileInformationByHandle 函数可能会失败,返回给定文件的部分信息或完整信息.

Depending on the underlying network components of the operating system and the type of server connected to, the GetFileInformationByHandle function may fail, return partial information, or full information for the given file.

一个快速测试表明它在使用 SMB/Samba 连接的 Linux 系统上使用符号链接按预期工作(相同的值),但是当使用指向相同的文件(FileIndex 相同,但 VolumeSerialNumber 不同).

A quick test shows that it works as expected (same values) with a symbolic link on a Linux system connected using SMB/Samba, but that it cannot detect that a file is the same when accessed using different shares that point to the same file (FileIndex is the same, but VolumeSerialNumber differs).