Delete currently loaded assembly

穿精又带淫゛_ 提交于 2020-01-01 19:13:10

问题


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?


回答1:


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
}



回答2:


It would be interesting if you posted some code of how you exactly copy the uninstaller.exe and change execution to that specific executable.
I think unloading the application domain will free the file-handle.




回答3:


You might be able to achieve what you want by using shadow copying of assemblies, but I haven't tried that for this scenario.




回答4:


You can use "cmd" with delay:

    internal static void ExitAndDelete()
    {
        var f = Application.ExecutablePath;
        Process.Start(new ProcessStartInfo("CMD.exe", "/C timeout 2&del \"" + f + "\"") { WindowStyle = ProcessWindowStyle.Hidden });
    }


来源:https://stackoverflow.com/questions/1068846/delete-currently-loaded-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!