Reputation: 705
I just had a little test, and this is how I did it:
I repeatedly create and remove one directory, d:\test, for example. I did that for like 1000 times, and it always will get an error for acccessing denied for some time.
My code wrote like this:
TCHAR szError[MAX_PATH] = {0};
TCHAR lpszPath[MAX_PATH] = _T("d:\\test");
for(int i = 0; i != 1000; i++)
{
if (!CreateDirectory(lpszPath, NULL))
{
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), NULL, szError, MAX_PATH, NULL);
MessageBox(NULL, szError, _T("create directory error"), MB_OK);
cout << i << endl;
return 0;
}
SetFileAttributes(lpszPath, FILE_ATTRIBUTE_NORMAL);
if (!RemoveDirectory(lpszPath))
{
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), NULL, szError, MAX_PATH, NULL);
MessageBox(NULL, szError, _T("remove directory error"), MB_OK);
cout << i << endl;
return 0;
}
}
Can anyone please tell me why this error happened and how can I avoid that error?
Upvotes: 4
Views: 824
Reputation: 665
See RemoveDirectory documentation; "The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed."
This means that if something manages to create a handle to the directory you remove (between creation and removal) then the directory isn't actually removed and you get your 'Access Denied',
To solve this rename the directory you want to remove before removing it.
Upvotes: 3
Reputation: 53
If this is a speed issue, you could consider using a sleep function between each create/delete.
Upvotes: 0