Nissim Nissim - 2 months ago 13
C# Question

Delete currently loaded assembly

In my application comes with an uninstaller.
Everything is working fine, except that I can't find no way to delete the uninstaller.exe file when it's all done.

I tried to copy the current assembly exe into a temp directory, but the file-handle of the original file is still locked.

Any ideas?


You will need to PInvoke to do this. MoveFileEx has the ability to schedule deleting the file on next reboot.

If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts.

Something like:

[return: MarshalAs (UnmanagedType.Bool)]
[DllImport ("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool MoveFileEx (string lpExistingFileName, string lpNewFileName, int dwFlags);

public static bool ScheduleDelete (string fileFullName) {
    if (!File.Exists (fileFullName))
        throw new InvalidOperationException ("File does not exist.");

    return MoveFileEx (fileFullName, null, 0x04); //MOVEFILE_DELAY_UNTIL_REBOOT = 0x04