Mfcでフォルダーを削除する方法を教えてください。

MFCでは、フォルダーを削除するには、まずCFileFindクラスを使ってフォルダー内のあらゆるファイルとサブフォルダーを列挙し、削除します。次に、CFile::Remove()関数を使ってフォルダー自体を削除します。

以下にサンプルコードを示します:

void DeleteFolder(CString folderPath)
{
    // 构建一个CFileFind对象来遍历文件夹中的文件和子文件夹
    CFileFind finder;
    
    // 构建文件夹路径
    CString searchPath = folderPath + _T("\\*.*");

    // 查找第一个文件
    BOOL bWorking = finder.FindFile(searchPath);

    while (bWorking)
    {
        bWorking = finder.FindNextFile();

        if (finder.IsDirectory() && !finder.IsDots())
        {
            // 删除子文件夹
            CString newPath = folderPath + _T("\\") + finder.GetFileName();
            DeleteFolder(newPath);
        }
        else
        {
            // 删除文件
            CString filePath = finder.GetFilePath();
            CFile::Remove(filePath);
        }
    }

    // 关闭查找
    finder.Close();

    // 删除文件夹本身
    RemoveDirectory(folderPath);
}

DeleteFolder() 関数を使用し、削除するフォルダのパスを引数として指定してください。ただし、このメソッドを使用するとフォルダ内のすべてのファイルとサブフォルダが削除され、フォルダ自体も削除されます。使用には注意してください。

bannerAds