Windows – How to delete Windows NTFS hard link (mklink /h) while original is in use

file managementhardlinkmklinkntfswindows

On a Windows NTFS file system, I have a file (say, orig.mp3). I open this file, through this path orig.mp3, in such a way that it is in use (say, by playing it in VLC).

Then I create a hard link (cmd /c mklink /h link.mp3 orig.mp3). This results in two NTFS paths pointing to exactly the same file.

Finally I try to delete linked file again (del link.mp3, or delete in Windows Explorer).

This fails with an error: "The process cannot access the file because it is being used by another process."

Why? And more importantly: how can I avoid this (apart from making sure no process has the original file in use)? Can I perhaps tell Windows to do a 'delayed delete', so that the linked file is automatically deleted when the original is no longer in use?

Best Answer

This is quite expected behavior, the hard link is just another name for the same file. E.g., if you have file A.PDF, create hard link B.PDF to the same file, it doesn't matter whether the file is opened under the name A.PDF or B.PDF - it's still the same file, so if this file is simply opened, you can't delete either link.

The actual reason is that the name is stored as an attribute in the file record of master file table (in case of NTFS) and since the file is opened, you can't delete either link (you can't modify opened file).

In this case there's nothing like original file, since both names belong to the same (and the only one) file and both names are equal. The file is actually deleted when link count reaches zero.

Related Question