Win32 file permission access violation when deleting temp file
I have an application where I am trying to implement "secure file overwrite":
- File creation (
A
) - Filling with
A
data - Copy
A
to final destination (B
) viaSHFileOperation
- Removing
A
withDeleteFile
However, step 4 DeleteFile
always returns ERROR_SHARING_VIOLATION. The whole process takes milliseconds, so I can't imagine who else would interfere with my file. A few questions:
- Is there a better Win32 (C / C ++) way to accomplish the above?
- How can I get more information about the "other process" that is preventing me from deleting a file
A
? - How do I softly (wink nudge nudge) force Windows to delete my temp file?
Any other suggestions are welcome
source to share
My best guess was that you need step 2.5). Close file descriptor created in 1)
What are you using to create / open the file?
If you are using CreateFile, make sure you close your file descriptor before calling for delete, and also make sure you specify the share flag FILE_SHARE_DELETE
.
HANDLE hFile = CreateFile("C:\\test.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, 0, NULL);
You can also make it easier to copy the file code using the Win32 CopyFile API .
source to share
One way to delete a file is to open it with FILE_FLAG_DELETE_ON_CLOSE
, which will ask the OS to automatically delete the file after the last handle to it is closed. If you create a file with FILE_SHARE_READ
, you SHFileOperation
must be able to read it in order to copy it, and then you can immediately close your file descriptor. When the shell closes its file descriptor, the file will be automatically deleted.
source to share
-
Try using Handles.exe from www.sysinternals.com to see if the file is in use and how the file works.
-
You can use GetLastError and FormatMessage to get more information about the last failed function:
Sample code:
char tx2[1024];
DWORD l;
if(l = GetLastError())
{
LPVOID lpMessageBuffer = 0;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
l,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language
(LPTSTR) &lpMessageBuffer,
0,
NULL
);
SetLastError(0);
MessageBox(NULL, tx2, "MyApplication", MB_ICONINFORMATION | MB_OK | (MB_SETFOREGROUND | MB_TOPMOST | MB_TASKMODAL));
}
source to share