在.NET程序中,因为运行中的程序是受系统保护的,不能自己删除自身的,所以自删除的思路是:在关闭本程序之前启动新的进程打开另一个程序,调用这个程序来删除原程序。然后再完成外部进程的销毁。
代码如下:
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteItself();
}
private static void DeleteItself()
{
string vBatFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\DeleteItself.bat";
using (StreamWriter vStreamWriter = new StreamWriter(vBatFile, false, Encoding.Default))
{
vStreamWriter.Write(string.Format(
":del\r\n" +
" del \"{0}\"\r\n" +
"if exist \"{0}\" goto del\r\n" +
"del %0\r\n", Application.ExecutablePath));
}
//************ 执行批处理
WinExec(vBatFile, 0);
//************ 结束退出
Application.Exit();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern uint WinExec(string lpCmdLine, uint uCmdShow);
可以在退出事件中调用DeleteItself();方法。