1. 程式人生 > >VC實現檔案自我刪除

VC實現檔案自我刪除

#include <afx.h>//需要使用mfc庫
#include <sys/stat.h>  //加入狀態顯示標頭檔案.
#include <ShellAPI.h>
#include <Shlobj.h>



BOOL SelfDel1()
{
	SHELLEXECUTEINFO sei;
	TCHAR szModule [MAX_PATH],szComspec[MAX_PATH],szParams [MAX_PATH];//字串陣列

	// 獲得檔名.
	if((GetModuleFileName(0,szModule,MAX_PATH)!=0) &&
		(GetShortPathName(szModule,szModule,MAX_PATH)!=0) &&
		(GetEnvironmentVariable("COMSPEC",szComspec,MAX_PATH)!=0))//獲取szComspec=cmd.exe
	{
		// 設定命令引數.
		lstrcpy(szParams,"/c del ");
		lstrcat(szParams, szModule);
		lstrcat(szParams, " > nul");

		// 設定結構成員.
		sei.cbSize = sizeof(sei);
		sei.hwnd = 0;
		sei.lpVerb = "Open";
		sei.lpFile = szComspec;//C:\Windows\system32\cmd.exe
		sei.lpParameters = szParams;//  /c del E:\adb\datasafe\Debug\datasafe.exe > nul
		sei.lpDirectory = 0;
		sei.nShow = SW_HIDE;
		sei.fMask = SEE_MASK_NOCLOSEPROCESS;

		// 執行shell命令.
		if(ShellExecuteEx(&sei))
		{
			// 設定命令列程序的執行級別為空閒執行,使本程式有足夠的時間從記憶體中退出. 
			SetPriorityClass(sei.hProcess,IDLE_PRIORITY_CLASS);
			SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);
			SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL);

			// 通知Windows資源瀏覽器,本程式檔案已經被刪除.
			SHChangeNotify(SHCNE_DELETE,SHCNF_PATH,szModule,0);
			return TRUE;
		}
	}
	return FALSE;
} 

BOOL SelfDel2()
{
	CStdioFile	file;
	CFileException fileEx;
	TCHAR szDir[MAX_PATH];
	TCHAR szModule[MAX_PATH];

	GetModuleFileName(0, szModule, sizeof(szModule));   // 獲得應用程式名.
	GetCurrentDirectory(MAX_PATH, szDir);               // 獲得檔案的當前目錄.

	CString strFilePath=CString(szDir)+"\\tempDel.bat";   // 臨時批處理檔名.

	if(!file.Open(strFilePath,CFile::modeWrite | 
		CFile::typeText | CFile::modeCreate,&fileEx))
	{
#ifdef _DEBUG
		afxDump << "The file could not be opened " << strFilePath<<"\n";
		afxDump << "Cause :"<<fileEx.m_cause << "\n";
#endif
		return FALSE;
	}

	CString strCmdLine1,strCmdLine2;
	strCmdLine1.Format("del %s\n",szModule);//del E:\adb\datasafe\Debug\datasafe.exe
	strCmdLine2.Format("del %%0\n");//del %0

	file.WriteString(strCmdLine1);                    // 寫刪除EXE的命令列.
	file.WriteString(strCmdLine2);                    // 寫刪除BAT的命令列.
	file.Close();

	WinExec(strFilePath,SW_HIDE);                     // 執行自行刪除操作.

	return TRUE;
}

void main()
{
	//SelfDel1();
	SelfDel2();
	
}