Click to See Complete Forum and Search --> : Delete Directory


ashokvishnu
July 25th, 2006, 01:25 AM
Hi All,

Pasted below is the code to delete a specified directory including its subdirectories and files. The issue is that I dont want the specified directory to be deleted, only its contents need to be deleted. That is if I specify D:\vcprojects\temp, then I dont want temp directory to be removed, only its subdirectories and files. How can I modify the code to get this done?

int DeleteDirectories( LPCTSTR refcstrRootDirectory)
{
// subdirectories have been found
HANDLE hFile; // Handle to directory
CString strFilePath; // Filepath
CString strPattern; // Pattern
WIN32_FIND_DATA FileInformation; // File information

strPattern = (CString)refcstrRootDirectory + _T("\\*.*");

hFile = ::FindFirstFile(strPattern, &FileInformation);

if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.Empty();
strFilePath = (CString) refcstrRootDirectory + "\\" + FileInformation.cFileName;

if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// Delete subdirectory
DeleteDirectories(strFilePath);
}
else
{
// Set file attributes
if(::SetFileAttributes(strFilePath ,
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();

// Delete file
if(::DeleteFile(strFilePath) == FALSE)
return ::GetLastError();

}
}
}
while(::FindNextFile(hFile, &FileInformation) == TRUE);

// Close handle
::FindClose(hFile);

DWORD dwError = ::GetLastError();
if(dwError != ERROR_NO_MORE_FILES)
return dwError;
else
{
// Set directory attributes
if(::SetFileAttributes(refcstrRootDirectory,
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();
_tprintf(_T("refcstrRootDirectory is %s\n"), refcstrRootDirectory);

// Delete directory
if(::RemoveDirectory(refcstrRootDirectory) == FALSE)
return ::GetLastError();
}

}
return 0;

}

humptydumpty
July 25th, 2006, 01:38 AM
What do you mean by content here .do you want to delete all the files and Folder Present inside the direcoty but not the directory itself am i right.if yes so use FindFirstFile() and FindNextFile() Method to get all the Files Present in the directory temp and delete them one by one.by this method you are able to remove the files. but your direcotry will be remain as it is.

virspb
July 25th, 2006, 02:08 AM
If FileInformation.cFileName is empty you delete your directory.
Make check an empty line or not

ashokvishnu
July 25th, 2006, 02:18 AM
I have solved the issue. Thanks.

golanshahar
July 25th, 2006, 02:37 AM
you can use ::SHFileOperation() (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/functions/shfileoperation.asp) with FO_DELETE

Cheers