删除目录以及目录下的所有文件(六)

时间:2021-03-06 12:08:17

 

删除目录以及目录下的所有文件 ( )
本文讲述如何删除目录以及其下的所有文件。
1.      创建一个对话框工程: DeleteFolder
2.      添加一个文本框控件来显示选择的文件夹 :m_Path
3.      添加一个“浏览按钮”,代码如下:
       CString ReturnPath ;
       TCHAR szPath [ _MAX_PATH ];
       BROWSEINFO bi ;
       bi . hwndOwner = NULL ;
       bi . pidlRoot = NULL ;
       bi . lpszTitle = _T ( " 请选择一个文件夹 " );
       bi . pszDisplayName = szPath ;
       bi . ulFlags = BIF_RETURNONLYFSDIRS ;
       bi . lpfn = NULL ;
       bi . lParam = NULL ;
       LPITEMIDLIST pItemIDList = SHBrowseForFolder (& bi );
       if ( pItemIDList )
       {
              if ( SHGetPathFromIDList ( pItemIDList , szPath ))
                     ReturnPath = szPath ;
       }
       else
              ReturnPath = "" ;
       m_Path . SetWindowText ( ReturnPath );
4.      添加一个函数,用来递归删除目录下的文件,如下:
void CDeleteFolderDlg :: DelFolder ( CString path )
{
       CFileFind file ;
       if ( path . Right (1) != "//" )
              path += "//*.*" ;
       BOOL bf ;
       bf = file . FindFile ( path );
       while ( bf )
       {
              bf = file . FindNextFile ();
              // 是文件时直接删除
              if (! file . IsDots () && ! file . IsDirectory ())
                     DeleteFile ( file . GetFilePath ());
              else if ( file . IsDots ())
                     continue ;
              else if ( file . IsDirectory ())
              {
                     path = file . GetFilePath ();
                     // 是目录时 , 继续递归调用函数删除该目录下的文件
                     DelFolder ( path );
                     // 目录为空后删除目录
                     RemoveDirectory ( path );
              }
       }
}
5.      添加一个按钮“删除”,代码如下:
       CString str ;
       m_Path . GetWindowText ( str );
       DelFolder ( str );
 
       if ( RemoveDirectory ( str ))
       {
              MessageBox ( " 删除成功! " );
              return ;
       }
完成,可以删除选定的目录及下的所有文件。