Search code examples
windowshardlink

Copy a folder programmatically without resolving hardlinks in Windows (Win32 API)


I want to copy an entire folder without resolving the hardlinks

example:

Folder1
  |
  +---File1
      File2
      HardLink3 -> File3

(HardLink3 created using fsutil hardlink create or mklink)

I want to copy this folder to

Folder2
  |
  +---File1
      File2
      HardLink3 -> File3

keeping Folder2\HardLink3 as a hardlink pointing to File3

Is there an Win32 API call to copy a entire folder with this semantic, or, if I need to do CopyFile / CreateHardLink file by file, what's the API call to check if a given file is a hardlink or not?


Solution

  • If you're absolutely sure that this is what you want to do, the easiest way to determine whether a file has multiple links (i.e., "is a hard link") is probably GetFileInformationByHandle.

    The nNumberOfLinks value returned will be 1 for a normal file and more than 1 if the file is (or has) a hard link.

    If I've understood your scenario correctly, it might be more sensible to check whether a file is hard linked to one of a specific set of files (the files in the "shared folder") rather than whether it is hard linked to any file anywhere. To do this, look at the File ID (nFileIndexHigh and nFileIndexLow) which for a hard link is the same as for the original file.

    In the latter case, as an optimization you could use GetFileInformationByHandleEx with the FileIdBothDirectoryInfo option to read the names and file IDs for all the files in a given directory in a single operation.