Self deletable application in C# in one executable

前端 未结 7 1838
北荒
北荒 2020-11-30 23:26

Is it possible to make an application in C# that will be able to delete itself in some condition.

I need to write an updater for my application but I don\'t want the

7条回答
  •  广开言路
    2020-11-30 23:42

    It's tricky without introducing yet another process (that you'd then want to delete as well, no doubt). In your case, you already have 2 processes - updater.exe and application.exe. I'd probably just have the Application delete updater.exe when it's spawned from there - you could use a simple command line arg, or an IPC call from updater.exe to application.exe to trigger it. That's not exactly a self deleting EXE, but fulfills the requirements I think.

    For the full treatment, and other options you should read the definitive treatment of self deleting EXEs. Code samples are in C (or ASM), but should be p/invokable.

    I'd probably try CreateFile with FILE_FLAG_DELETE_ON_CLOSE for updater.exe with something like (psuedo code):

     var h = CreateFile(
                "updater.exe", 
                GENERIC_READ | GENERIC_WRITE, 
                FILE_SHARE_DELETE, 
                NULL, 
                CREATE_NEW, 
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE
             );
    
     byte[] updaterBytes = GetUpdaterBytesFromWeb();
     File.WriteAllBytes("updater.exe", updaterBytes);
    
     Process.Start("updater.exe");
    

    Once application.exe exits, updater.exe has a file handle of 1. When updater.exe exits, it drops to 0 and should be deleted.

提交回复
热议问题