Hi Kid,
I didn't try it myself but you might try using CreateFile to open your
exe with FILE_FLAG_DELETE_ON_CLOSE.
http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx
MoveFileEx with MOVEFILE_DELAY_UNTIL_REBOOT and NULL as destination
[Removed followups to groups where this would not apply.]
Just a side note---if your application intends to be portable for any
reason or will become portable, be sure to check
System.Environment.OSVersion.Platform before doing this. Under UNIX
and UNIX-like systems, you can just delete the file while the process
is running:
/*
* self-delete-unix.cs - Delete oneself and then run.
*/
using System;
using System.IO;
using System.Threading;
public class Program {
public static int Main(string[] args) {
string progfile = "self-delete-unix.exe";
File.Delete(progfile);
Hi();
Thread.Sleep(10000);
Hi2();
return(0);
}
public static void Hi() {
Console.WriteLine("I have been deleted.");
}
public static void Hi2() {
Console.WriteLine("I have been deleted.");
}
}
This works because on UNIX systems, files will be removed from
directory listings, but won't actually be deleted until there are no
more processes holding then open. Once the last file descriptor
referring to the file is closed, the operating system will finalize
removal of the file; before then, it will appear as if deleted (e.g.,
be detached from the directory and so forth, and no new processes will
be able to open it). Once closed, all that is left to do is free the
blocks the file occupied.
Also, keep in mind for portable applications that if you delete a file
successfully, that doesn't mean you closed all open refs (on POSIX
systems anyway). Just an FYI.
--- Mike