discodowney
discodowney

Reputation: 1507

In code - Deleting a folder with files

Im trying to write code that will delete a folder that has files in it. Ive tried a couple of ways and i get the same problem each time. I delete the files in the folder and the folder seemingly fine. But it seems some sort of reference to the folder still exists.

I step thorugh my code and i get to the delete functions(s) and they seem to pass fine. Then I go to Windows Explorer and try to access the folder i just deleted. It is still there even though the code says it deleted it, but when i click on it it says "Access Denied". One of the methods I tried did remove the folder from windows explorer, but when i try to create a folder with the same name and location I get an error and from GetLastError it says E_ACCESSDENIED.

So is there something i have to do to properly delete a folder?

One method I used was using SHFileOperation. Another was to use FindFirstData and delete all the files then use RemoveDirectory to delete the empty folder. Both lead me to this Access Denied problem.

EDIT: Here is my SHFileOperation. https://stackoverflow.com/questions/9291995/cant-get-shfileoperation-to-delete-a-directory-with-more-than-one-file

Upvotes: 0

Views: 10081

Answers (3)

herohuyongtao
herohuyongtao

Reputation: 50657

Check out the remove_folder() I wrote in C++ here, which I answered a similar question as yours. It doesn't use any 3rd-party libraries like boost.

Upvotes: 0

Mahesh
Mahesh

Reputation: 11

You may use

system ( "RD /S /Q [path] " );

works well but deletes everything in the folder permanently. So backup before u use it!!

Upvotes: 1

Sapan Diwakar
Sapan Diwakar

Reputation: 10946

You can use Boost.FileSystem.

In your case that would be

boost::filesystem::remove_all(yourPath)

This will remove all the files in the path. Then use:

RemoveDirectory( LPCTSTR lpPathName );    // Windows only

Upvotes: 1

Related Questions