Windows删除文件夹

方法一:

利用API函数SHFileOperation实现的删除函数,能够一次删除目录及其下面的子目录和文件 或者 删除单个的文件

// 删除文件(第二个参数bDelete表示是否删除至回收站,默认删除到回收站)
BOOL RecycleFileOrFolder(CString strPath, BOOL bDelete/*=FALSE*/)
{
    strPath += '\0';
    SHFILEOPSTRUCT  shDelFile;
    memset(&shDelFile,0,sizeof(SHFILEOPSTRUCT));
    shDelFile.fFlags |= FOF_SILENT;                // 不显示进度
    shDelFile.fFlags |= FOF_NOERRORUI;            // 不报告错误信息
    shDelFile.fFlags |= FOF_NOCONFIRMATION;        // 直接删除,不进行确认
 
    // 设置SHFILEOPSTRUCT的参数为删除做准备
    shDelFile.wFunc = FO_DELETE;        // 执行的操作
    shDelFile.pFrom = strPath;            // 操作的对象,也就是目录(注意:以“\0\0”结尾)
    shDelFile.pTo = NULL;                // 必须设置为NULL
    if (bDelete) //根据传递的bDelete参数确定是否删除到回收站
    {    
        shDelFile.fFlags &= ~FOF_ALLOWUNDO;    //直接删除,不进入回收站
    } 
    else 
    {           
        shDelFile.fFlags |= FOF_ALLOWUNDO;    //删除到回收站
    }
 
    BOOL bres = SHFileOperation(&shDelFile);    //删除
    return !bres;
}

方法二:

bool DeleteDirectory(const CString& strDirName)
{
    CFileFind tempFind;
    TCHAR sTempFileFind[200];
    _tcscpy_s(sTempFileFind, strDirName);
    _tcscat_s(sTempFileFind, L"\\*.*");
    BOOL IsFinded = tempFind.FindFile(sTempFileFind);
    while (IsFinded)
    {
        IsFinded = tempFind.FindNextFile();
        if (!tempFind.IsDots())
        {
            CString strPath;
            strPath += strDirName;
            strPath += L"\\";
            strPath += tempFind.GetFileName();
            if (tempFind.IsDirectory())
            {
                DeleteDirectory(strPath);
            }
            else
            {
                SetFileAttributes(strPath, FILE_ATTRIBUTE_NORMAL); //去掉文件的系统和隐藏属性
                DeleteFile(strPath);
            }
        }
    }
    tempFind.Close();
    if (!RemoveDirectory(strDirName))
    {
        return FALSE;
    }
    return TRUE;
}

猜你喜欢

转载自www.cnblogs.com/2018shawn/p/12725544.html