Vista introduced a lesser-known feature called Restart Manager, which can help you release file locks with user-mode code. Since you marked it as C ++, based on this article, here is a small code example:
#include <RestartManager.h> #pragma comment(lib ,"Rstrtmgr.lib") BOOL ReleaseFileLock(LPCTSTR pFilePath) { BOOL bResult = FALSE; DWORD dwSession; WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = { 0 }; DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey); if (dwError == ERROR_SUCCESS) { dwError = RmRegisterResources(dwSession, 1, &pFilePath, 0, NULL, 0, NULL); if (dwError == ERROR_SUCCESS) { UINT nProcInfoNeeded = 0; UINT nProcInfo = 0; RM_PROCESS_INFO rgpi[1]; DWORD dwReason; dwError = RmGetList(dwSession, &nProcInfoNeeded, &nProcInfo, rgpi, &dwReason); if (dwError == ERROR_SUCCESS || dwError == ERROR_MORE_DATA) { if(nProcInfoNeeded > 0) { //If current process does not have enough privileges to close one of //the "offending" processes, you'll get ERROR_FAIL_NOACTION_REBOOT dwError = RmShutdown(dwSession, RmForceShutdown, NULL); if (dwError == ERROR_SUCCESS) { bResult = TRUE; } } else bResult = TRUE; } } } RmEndSession(dwSession); SetLastError(dwError); return bResult; }
ahmd0 source share