c# - 如何确定两个文件系统 URI 是否指向同一资源?

标签 c# .net io

如果我有两个不同的文件路径,我如何确定它们是否指向同一个文件?

这可能是这种情况,例如,如果用户连接了一个网络驱动器,它指向某个网络资源。例如驱动器 S: 映射到\servercrm\SomeFolder。

那么这些路径实际上指向同一个文件:

S:\somefile.dat

\\servercrm\SomeFolder\somefile.dat

我怎样才能检测到这个?我需要对其进行编码,使其适用于路径可能以不同方式指向同一文件的所有场景。

最佳答案

我不知道是否有直接在 C# 中执行此操作的简单方法,但您可以对 GetFileInformationByHandle 执行非托管调用(pinvoke 页面 here )将返回 BY_HANDLE_FILE_INFORMATION结构。这包含三个字段,可以将它们组合起来以唯一标识一个文件:

dwVolumeSerialNumber: The serial number of the volume that contains a file.

...

nFileIndexHigh: The high-order part of a unique identifier that is associated with a file.

nFileIndexLo: The low-order part of a unique identifier that is associated with a file.

The identifier (low and high parts) and the volume serial number uniquely identify a file on a single computer. To determine whether two open handles represent the same file, combine the identifier and the volume serial number for each file and compare them.

请注意,这仅在两个引用都从同一台机器声明时才有效。


编辑添加:

根据 this question这可能不适用于您遇到的情况,因为 dwVolumeSerialNumber 可能不同,因为共享定义不同。不过,我会先尝试一下,因为我一直认为卷序列号是特定于驱动器的,而不是特定于路径的。不过,我从来不需要真正证明这一点,所以我可能(而且很可能)错了。

关于c# - 如何确定两个文件系统 URI 是否指向同一资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/852275/

相关文章:

c# - asp.net mvc 4路由错误

c# - Type.GetType ("System.Net.WebException")返回 null

c# - 如何强制 WeakReference 死亡?

java - BufferedWriter - 程序执行期间流过早关闭

java - 如何从浏览器保存 .pdf?

c# - 通过网络复制文件(需要身份验证)

c# - ASP.net Javascript 回传

c# - 远程桌面上的串口

.net - .Net Core 中用于多个框架的预处理器指令

c# - .net 标准库中的 HttpContext