Page 1 of 1

Deleting a Directory including all files and sub directories

Posted: Tue Aug 23, 2005 3:14 pm
by ashish

Code: Select all

bool CMyClass::DeleteDirectory(wxString filename)
{
	bool dir_empty = false;
	{
		wxDir dir(filename);
		if ( !dir.IsOpened() )
		{
			// deal with the error here - wxDir would already log an error message
			// explaining the exact reason of the failure
			return FALSE;
		}
		wxString file;
		
		bool cont = dir.GetFirst(&file);
		file = filename + wxFileName::GetPathSeparator()+ file;
		while ( cont )
		{
			if(wxFileName::FileExists(file)) wxRemoveFile(file);
			if( wxFileName::DirExists(file)) DeleteDirectory(file);
			cont = dir.GetNext(&file);
			file = filename + wxFileName::GetPathSeparator()+ file;
		}
		if(!(dir.HasFiles() || dir.HasSubDirs()))dir_empty = true;
	}
	if(dir_empty){
		bool error = wxRmdir(filename);
		return TRUE;
	}
	return FALSE;
}

Posted: Tue Aug 23, 2005 3:42 pm
by ssigala
Good work ashish! :)

P.S. maybe the while loop can be reworked a bit like this:

Code: Select all

                wxString file;
                bool cont = dir.GetFirst(&file);
                while ( cont )
                {
                        file = filename + wxFileName::GetPathSeparator()+ file;
                        if(wxFileName::FileExists(file)) wxRemoveFile(file);
                        if( wxFileName::DirExists(file)) DeleteDirectory(file);
                        cont = dir.GetNext(&file);
                }

Posted: Tue Aug 23, 2005 4:00 pm
by vdell
There is also another version @ http://forums.wxwidgets.org/viewtopic.php?t=2519

Posted: Tue Aug 23, 2005 8:26 pm
by Jorg
Minor suggestion, use the wxFileName::AppendDir function instead of dealing with the path seperator. The AppendDir will deal with it for you. By using a wxFileName to begin with (instead of wxString) you do not have to concatenate all the time ;-)

But besides that it's another useful contribution to the Code Dump, thanks!
- Jorgen