我準備寫一個逗比的應用,然而我擔心被小夥伴看到這個應用的檔案進而知道是我寫的,于是我就需要實作讓應用能自删除的功能。核心實作方法就是調用 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);
}
本文所有代碼放在 github 和 gitee 歡迎通路
可以通過如下方式擷取本文代碼
先建立一個空檔案夾,接着使用指令行 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 檔案夾
部落格園部落格隻做備份,部落格釋出就不再更新,如果想看最新部落格,請到 https://blog.lindexi.com/
本作品采用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協定進行許可。歡迎轉載、使用、重新釋出,但務必保留文章署名[林德熙](http://blog.csdn.net/lindexi_gd)(包含連結:http://blog.csdn.net/lindexi_gd ),不得用于商業目的,基于本文修改後的作品務必以相同的許可釋出。如有任何疑問,請與我[聯系](mailto:[email protected])。