我准備寫一個逗比的應用,然而我擔心被小伙伴看到這個應用的文件從而知道是我寫的,於是我就需要實現讓應用能自刪除的功能。核心實現方法就是調用 cmd 傳入命令行,等待幾秒之后刪除文件
應用程序在運行時,是不能將 exe 文件進行刪除的。但是可以將 exe 改名以及在驅動器內進行移動文件
刪除應用程序可以讓 cmd 進行刪除,在 cmd 可以使用 timeout 命令延遲,然后通過 && 進行執行后續邏輯,從而實現延遲執行命令。讓 cmd 延遲執行 DEL 命令進行刪除應用,在應用調用刪除之后,讓應用程序結束即可
代碼如下
static void Main(string[] args)
{
var fileName = Process.GetCurrentProcess().MainModule.FileName;
DelayDeleteFile(fileName, 2);
}
private static void DelayDeleteFile(string fileName, int delaySecond = 2)
{
fileName = Path.GetFullPath(fileName);
var folder = Path.GetDirectoryName(fileName);
var currentProcessFileName = Path.GetFileName(fileName);
var arguments = $"/c timeout /t {delaySecond} && DEL /f {currentProcessFileName} ";
var processStartInfo = new ProcessStartInfo()
{
Verb = "runas", // 如果程序是管理員權限,那么運行 cmd 也是管理員權限
FileName = "cmd",
UseShellExecute = false,
CreateNoWindow = true, // 如果需要隱藏窗口,設置為 true 就不顯示窗口
Arguments = arguments,
WorkingDirectory = folder,
};
Process.Start(processStartInfo);
}
可以通過如下方式獲取本文代碼
先創建一個空文件夾,接着使用命令行 cd 命令進入此空文件夾,在命令行里面輸入以下代碼,即可獲取到本文的代碼
git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 62aeb3d73ca3bf97f24a7283a61bce8b7774e799
以上使用的是 gitee 的源,如果 gitee 不能訪問,請替換為 github 的源
git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
獲取代碼之后,進入 QarnafahayWalllukerrairbar 文件夾
