Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateSymbolicLink on windows 10

Tags:

symlink

winapi

ever since they were first introduced, creating a symbolic link required a full administrator. Running from a normal or from a non-elevated process CreateSymbolicLink would fail.

In windows 10, CreateSymbolicLink fails as well in these circumstances, that is it doesn't create anything, however it returns a success code (!) and GetLastError is 0 too. So there's no way to detect the error other than checking if the symlink file exists

Looks like a bug in windows 10?

like image 420
nikos Avatar asked Oct 28 '25 07:10

nikos


2 Answers

Have experienced the same. But: The success code you seem to get is an error code. So it seems the have changed the return type of CreateSymbolicLink from BOOLEAN to int

like image 91
Hermann Schinagl Avatar answered Oct 31 '25 10:10

Hermann Schinagl


This workarround works for me:
Change the return value into an integer.

1 = success
for all other values call GetLastWin32Error

[DllImport("kernel32.dll", EntryPoint = "CreateSymbolicLinkW", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, SYMBOLIC_LINK_FLAG dwFlags);

public static int CreateSymbolicLinkFix(string lpSymlinkFileName, string lpTargetFileName, int dwFlags) {
    var result = CreateSymbolicLink(lpSymlinkFileName, lpTargetFileName, dwFlags);
    if (result == 1) return 0; // Success
    return Marshal.GetLastWin32Error();
}
like image 33
kux Avatar answered Oct 31 '25 12:10

kux