我构建了一个基本的Windows窗体应用程序 我想这样做,以便我的程序在我选择的日期之后删除.
具体来说,当有人点击.exe运行它时,如果它在特定日期之后,则删除.exe.这可能吗?如果是,我该怎么做?
我认为我的代码看起来像这样:
DateTime expiration = new DateTime(2013, 10, 31) //Oct. 31, 2013
If (DateTime.Today > expiration)
{
//command to self-delete
}
else
{
//proceed normally
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*dgi 14
这样可以运行命令行操作来删除自己.
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"
});
Run Code Online (Sandbox Code Playgroud)
您必须确保在要删除文件时已关闭应用程序.我会建议类似下面的东西 - 当然你需要做一些修改.
以下示例适用于Windows,需要针对其他操作系统进行修改.
/// <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");
}
Run Code Online (Sandbox Code Playgroud)
它在运行时无法删除自身,因为它的可执行文件和库文件将被锁定。您可以编写第二个程序,它接受进程 ID 作为参数,等待该进程终止,然后删除第一个程序。将其作为资源嵌入到主应用程序中,然后将其提取到%TEMP%、运行并退出。
这种技术通常与自动更新程序结合使用,而且它绝对不是万无一失的。