Thursday, November 10, 2016

boost::filesystem::remove_all, RemoveDirectory WinAPI function and 'The directory is not empty' error

Problem

Sometime boost::filesystem::remove_all on windows (or RemoveDirectoryA/RemoveDirectoryW WinAPI functions, which are called into remove_all windows implementation) returns stupid error 'The directory is not empty'.

Problem solving in short

Windows have some problems with long paths (which length more than 260 symbols), and if you want to handle such paths, you need to write instead of C:\my_long_filename stuff like \\?\C:\my_long_filename.
If you have directory C:\dir where located file with long name, RemoveDirectory winapi function called with this path returns error 'The directory is not empty'. But if you call it with \\?\C:\dir parameter - it will work fine.
So, instead of using boost::filesystem::remove_all you can use something like that:

void RemoveAll(const std::wstring & path)
{
    std::wstring current_path = path;

    if (current_path.substr(0, 4) != L"\\\\?\\")
    {
        current_path = L"\\\\?\\" + current_path;
    }

    boost::filesystem::remove_all(current_path);
}