Deleting hard links problem

time to read 2 min | 214 words

This code fails:

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);

static void Main()
{
    var writer = File.CreateText("test.txt");
    writer.Write("test");
    writer.Flush();

    CreateHardLink("hard_link.txt", "test.txt", IntPtr.Zero);


    File.Delete("hard_link.txt");

}

The problem here is that the hard_link.txt file is considered to be open. What I would expect to happen is that the delete would succeed in removing the directory entry, but keep the file. In other words, I would only expect it to fail if this is the last directory entry for the file (resulting in an actual delete).

For now I changed this to try to delete, but on failure, mark the file to be deletes on the next reboot.