C#内置的.exe是否可以自删除? [英] Is it possible for a C# built .exe to self-delete?
问题描述
我构建了一个基本的Windows Form应用程序.我想这样做,以便我的程序在我选择的日期之后删除自己.
I built a basic Windows Form app. I want to make it so that my program deletes itself after a date of my choosing.
具体来说,当有人单击.exe来运行它时,如果在某个日期之后,该.exe将被删除.这可能吗?如果是,该怎么办?
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
}
推荐答案
您必须确保,要删除文件时,您的应用程序已关闭.我建议与以下内容类似-当然,您需要进行一些修改.
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.
以下示例在Windows上运行,并且需要针对其他操作系统进行修改.
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");
}
这篇关于C#内置的.exe是否可以自删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!