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
}
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"
});
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With