Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a C# built .exe to self-delete?

Tags:

c#

I built a basic Windows Form app. I want to make it so that my program deletes itself after a date of my choosing.

Specifically, when someone clicks on the .exe to run it, and if it's after a certain date, the .exe is deleted. Is this possible? If yes, how do I do this?

I think my code would look something like this:

DateTime expiration = new DateTime(2013, 10, 31) //Oct. 31, 2013

If (DateTime.Today > expiration) 
{
    //command to self-delete
}
else  
{
    //proceed normally
}
like image 885
phan Avatar asked Oct 30 '13 16:10

phan


2 Answers

This works, runs a commandline operation to delete yourself.

Process.Start( new ProcessStartInfo()
{
    Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Application.ExecutablePath +"\"",
    WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe"
});
like image 145
BenVlodgi Avatar answered Oct 05 '22 01:10

BenVlodgi


You must make sure, that your application is already closed when you want to delete the file. I would suggest something similar to the following one - you will need some modifications of course.

The following example works on windows and needs to be modified for other operating systems.

/// <summary>
/// Represents the entry point of our application.
/// </summary>
/// <param name="args">Possibly spcified command line arguments.</param>
public static void Main(string[] args)
{
    string batchCommands = string.Empty;
    string exeFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("file:///",string.Empty).Replace("/","\\");

    batchCommands += "@ECHO OFF\n";                         // Do not show any output
    batchCommands += "ping 127.0.0.1 > nul\n";              // Wait approximately 4 seconds (so that the process is already terminated)
    batchCommands += "echo j | del /F ";                    // Delete the executeable
    batchCommands += exeFileName + "\n";
    batchCommands += "echo j | del deleteMyProgram.bat";    // Delete this bat file

    File.WriteAllText("deleteMyProgram.bat", batchCommands);

    Process.Start("deleteMyProgram.bat");
}
like image 36
Markus Safar Avatar answered Oct 05 '22 00:10

Markus Safar