Invalid handle error when calling CloseHandle on FindFirstFileW handle in C++

I’m working on a C++ project in Visual Studio and I’m having trouble with a directory search function. The code works fine at first but crashes when I try to close the file handle.

Here’s my directory searching function:

wstring DirectoryScanner::LocateTargetDirectory(const wstring& startPath, wstring targetDirName)
{
    wstring resultDir = L"";
    wstring searchPath = startPath + L"\\*";
    WIN32_FIND_DATAW fileData;
    HANDLE hFind = FindFirstFileW(searchPath.c_str(), &fileData);
    
    if (hFind != INVALID_HANDLE_VALUE)
    {
        vector<wstring> subdirectories;

        do
        {
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((!lstrcmpW(fileData.cFileName, L".")) || (!lstrcmpW(fileData.cFileName, L"..")))
                    continue;
            }

            wstring currentPath = startPath + L"\\" + wstring(fileData.cFileName);

            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if (fileData.cFileName == targetDirName)
                {
                    resultDir = fileData.cFileName;
                    return resultDir;
                }
                subdirectories.push_back(currentPath);
            }
        } while (FindNextFileW(hFind, &fileData));

        CloseHandle(hFind);

        for (auto it = subdirectories.begin(); it != subdirectories.end(); ++it)
            LocateTargetDirectory(*it, targetDirName);
    }

    return resultDir;
}

The function starts running normally but when it reaches the CloseHandle line, I get this error:

Exception at 0x76D712C7 in MyApp.exe: 0xC0000008: An invalid handle was specified.

My project setup includes a static library with this class and a console application that uses it. Some of the folder names contain Cyrillic characters but I don’t think that’s causing the issue. What could be wrong with my handle management and how do I fix this problem?

You’re right about CloseHandle vs FindClose, but there’s another big issue. You’re calling CloseHandle(hFind) inside the loop, then keep using hFind for recursive calls without cleaning up properly. Switch to FindClose and move it right after the while loop ends, before you start recursing into subdirectories. Also, your recursive calls aren’t capturing return values - you’ll miss finding the target if it’s in a subdirectory. Store those results and check if you found a valid path before continuing the search.

You’re using CloseHandle instead of FindClose - that’s causing the invalid handle error. But there’s a bigger problem with your function logic. You’re doing FindClose at the right time, but your recursive calls aren’t passing results back up the chain. When a subdirectory search finds something, that result just disappears because you’re not checking what the recursive calls return. Fix the recursive section to actually capture results - if a recursive call returns a non-empty string, you found your target and should return right away. Also heads up: you’re only returning the directory name, not the full path. That might bite you depending on what you need.

uh, just a heads up, u should use FindClose instead of CloseHandle for handles returned by FindFirstFileW. that’s likely causing the invalid handle error. make sure to fix that!