65.9K
CodeProject is changing. Read more.
Home

Writing a self destructing exe file

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.23/5 (25 votes)

Apr 27, 2003

Public Domain
viewsIcon

191051

Explains how you can have a program delete itself once it has finished running without a reboot

Introduction

Uninstall programs typically want to delete themselves at the end of the un-installation, but executable cannot delete itself by simply calling the DeleteFile function. By calling the Selfdestruct() function showed below before program exit, the calling executable will be destroyed as soon as possible. The method shown in this article works on all Win32 platforms and there is no need to reboot.

Using the code

Just call the Selfdestruct() function before program exit.

// this is the name of the temporary .bat file
static const char tempbatname[] = "_uninsep.bat" ;

void Selfdestruct() 
{
  // temporary .bat file
  static char templ[] = 
    ":Repeat\r\n"
    "del \"%s\"\r\n"
    "if exist \"%s\" goto Repeat\r\n"
    "rmdir \"%s\"\r\n"
    "del \"%s\"" ;


  char modulename[_MAX_PATH] ;    // absolute path of calling .exe file
  char temppath[_MAX_PATH] ;      // absolute path of temporary .bat file
  char folder[_MAX_PATH] ;

  GetTempPath(_MAX_PATH, temppath) ;
  strcat(temppath, tempbatname) ;

  GetModuleFileName(NULL, modulename, MAX_PATH) ;
  strcpy (folder, modulename) ;
  char *pb = strrchr(folder, '\\');
  if (pb != NULL)
    *pb = 0 ;

  HANDLE hf ;
  
  hf = CreateFile(temppath, GENERIC_WRITE, 0, NULL, 
              CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) ;
  
  if (hf != INVALID_HANDLE_VALUE)
  {
    DWORD len ;
    char *bat ;

    bat = (char*)alloca(strlen(templ) + 
               strlen(modulename) * 2 + strlen(temppath) + 20) ;

    wsprintf(bat, templ, modulename, modulename, folder, temppath) ;

    WriteFile(hf, bat, strlen(bat), &len, NULL) ;
    CloseHandle(hf) ;

    ShellExecute(NULL, "open", temppath, NULL, NULL, SW_HIDE);
  }
}

How it works

Let's assume the executable that wants to destroy itself is located in c:\myfolder\selfdestruct.exe. The Selfdestruct() function will create following .bat in the computers temp folder and then launches it:

    :Repeat
    del "c:\myfolder\selfdestruct.exe"
    if exist "c:\myfolder\selfdestruct.exe" goto Repeat
    rmdir "c:\myfolder"
    del "c:\temp\_uninsep.bat" ;

The .bat file will try to delete the c:\myfolder\selfdestruct.exe over and over until it finally succeeds (that is as soon as selfdestruct.exe has finished execution. Then it tries to remove the containing folder (here c:\myfolder) which will work only if it is empty and finally deletes itself. Fortunately .bat files can delete themselves.