I am trying to remove a symbolic link that I created.
You can see it in the Object manager (WinObj):
I am trying to delete the folder. I saw here that I need to open a handle to object with NtOpenSymbolicLinkObject
and then use NtMakeTemporaryObject
to delete it.
I tried to do it with number of different calls to DeleteSymbolicLink
, and the function NtOpenSymbolicLinkObject
doesn't succeed to get handle. Here is the code I used:
[DllImport("ntdll.dll")]
public static extern int NtOpenSymbolicLinkObject(
out SafeFileHandle LinkHandle,
uint DesiredAccess,
ref ObjectAttributes ObjectAttributes);
public enum NtStatus : uint
{
Success = 0x00000000
}
[DllImport("ntdll.dll")]
public static extern NtStatus NtMakeTemporaryObject(SafeFileHandle Handle);
[DllImport("ntdll.dll")]
static extern int NtClose(SafeFileHandle handle);
public static void DeleteSymbolicLink(SafeKernelObjectHandle directory, string path){
uint DELETE = 0x00010000;
SafeFileHandle handle;
ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive, directory, null, null);
if (NtOpenSymbolicLinkObject( out handle, DELETE, ref obja) == 0x00000000)
{
NtMakeTemporaryObject( handle);
NtClose( handle);
}
}
public static void CreateSymlink(string inputPath, string outPath)
{
string inputFilename = Path.GetFileName(inputPath);
string inputDir = Path.GetDirectoryName(inputPath);
JunctionPoint.Create(@"\RPC Control", inputDir, true);
CreateSymbolicLink(null, @"\RPC Control\" + inputFilename, outPath);
}
static SafeKernelObjectHandle CreateSymbolicLink(SafeKernelObjectHandle directory, string path, string target)
{
using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive, directory, null, null))
{
IntPtr handle;
StatusToNtException(NtCreateSymbolicLinkObject(out handle, GenericAccessRights.MaximumAllowed, obja, new UnicodeString(target)));
return new SafeKernelObjectHandle(handle, true);
}
}
static void Main(string[] args){
CreateSymlink("C:\tmp\MyFile.txt", fileToDelete);
DeleteSymbolicLink(null, @"\RPC Control\" + "\??\C:\Windows\win2.ini");
DeleteSymbolicLink(null, @"\RPC Control\" + "MyFile.txt");
DeleteSymbolicLink(null, @"\RPC Control\" + "C:\tmp\MyFile.txt");
DeleteSymbolicLink(null, "MyFile.txt");
DeleteSymbolicLink(null, "C:\tmp\MyFile.txt");
DeleteSymbolicLink(null, "\??\C:\Windows\win2.ini");
}