CreateFile Fails for SymLink to File in Parent Fol

2019-08-04 19:27发布

问题:

In reference to this question:

File.Copy() and Symbolic Links

I find that the line

SafeFileHandle fileHandle = 
    CreateFile(symlink.FullName, 0, 2, 
               IntPtr.Zero, 
               CREATION_DISPOSITION_OPEN_EXISTING, 
               FILE_FLAG_BACKUP_SEMANTICS, 
               IntPtr.Zero);

is failing with the error

The system cannot find the file specified

for the following very specific case:

Original file is in a parent directory

C:\Temp\SymlinkUnitTest\Original.txt [real file]

Symbolic link is in a real subdirectory

C:\Temp\SymlinkUnitTest\Work\Symlink.txt [sym link to above file]

It seems to work in many other cases (all unit tests in the referenced post pass).

Is there something special about this particular case?

For reference, here's the unit test that is failing:

[TestMethod]
public void FileSymlinkWork()
{
    string file = @"C:\Temp\SymlinkUnitTest\Work\Symlink.txt";
    Assert.IsTrue(File.Exists(file)); // Succeeds 

    // Following line throws Exception:
    string actual = new FileInfo(file).GetSymbolicLinkTarget();
    Assert.IsTrue(actual.EndsWith(@"SymlinkUnitTest\Original.txt"));
}