SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFromIDList Not Working

545 Views Asked by At

I am trying to get SHBrowseForFolder with BIF_BROWSEFORCOMPUTER to work, in order to allow a user to select a computer on the network.

I can get the dialog to display and allow selection of a network computer, the OK button is enabled, but when I click OK, even though the function returns a PIDL that is not NULL, the call to SHGetPathFromIDList fails and the path to the remote computer is therefore not available.

Am I calling the right function to get the remote computer name?

Code:

UINT __stdcall BrowseForFolder()
{
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    // Setup browse structure.
    BROWSEINFO bi = { 0 };
    bi.lpszTitle = TEXT("Pick a Directory");
    bi.hwndOwner = GetForegroundWindow();
    bi.ulFlags = BIF_USENEWUI | BIF_BROWSEFORCOMPUTER;

    // Call 
    LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

    // Get path.
    if (pidl)
    {
        // get the name of the folder
        TCHAR path[MAX_PATH];
        if (SHGetPathFromIDList(pidl, path))    // This function fails and path is NULL.
        {
            MessageBox(GetForegroundWindow(), path, TEXT("Path"), MB_ICONINFORMATION);
        }

        // free memory used
        CoTaskMemFree(pidl);
    }

    CoUninitialize();

    return ERROR_SUCCESS;
}
1

There are 1 best solutions below

1
Remy Lebeau On

SHGetPathFromIDList() only works for filesystem paths. A network computer is not part of the filesystem, so you can't use SHGetPathFromIDList() for this task.

If you need the name of the selected computer, you can either:

UINT __stdcall BrowseForFolder()
{
    TCHAR szComputerName[MAX_COMPUTERNAME_LENGTH] = {};

    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    // Setup browse structure.
    BROWSEINFO bi = { 0 };
    bi.lpszTitle = TEXT("Pick a Computer");
    bi.hwndOwner = GetForegroundWindow();
    bi.pszDisplayName = szComputerName;
    bi.ulFlags = BIF_USENEWUI | BIF_BROWSEFORCOMPUTER;

    // Call 
    LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

    // Get path.
    if (pidl)
    {
        MessageBox(GetForegroundWindow(), szComputerName, TEXT("Computer Name"), MB_ICONINFORMATION);

        // free memory used
        CoTaskMemFree(pidl);
    }

    CoUninitialize();

    return ERROR_SUCCESS;
}