检查给定路径是否是特殊文件夹路径?

时间:2015-08-11 12:14:56

标签: windows winapi special-folders

在Windows上,可以使用<ul class="nav nav-tabs nav-justified"> <li>..</li> .. SHGetKnownFolderPath获取任何特殊的文件夹路径(如果我记得最后一个)。但是,我想反过来,我有一个路径,想要知道它属于哪个特殊文件夹,如果有的话。我更喜欢这种方法,因为要查明给定路径是否在特定的特殊文件夹中,我必须枚举所有用户的所有特殊文件夹,这有点难看,但如果没有别的办法,天空是限制:)

我搜索了它但找不到任何有用的东西。那么WinApi有这样的功能吗?

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用IKnownFolderManager::FindFolderFromPath

自Vista以来可用。

PS:查看CComPtr<>类,以便更简单地与COM接口。

以下是我刚刚编写的一个示例,展示了如何使用它:

#include <atlsafe.h>
#include <Shobjidl.h>
#include <comdef.h>

void PrintKnownFolder( const CComPtr<IKnownFolder>& folder )
{
    KNOWNFOLDER_DEFINITION def;
    HRESULT hr = folder->GetFolderDefinition( &def );
    if( SUCCEEDED(hr) ) {
        std::wcout << L"Result: " << def.pszName << std::endl;
        FreeKnownFolderDefinitionFields( &def );
    } else {
        _com_error err(hr);
        std::wcout << L"Error while querying GetFolderDefinition: " << err.ErrorMessage() << std::endl;
    }
}


class CCoInitialize
{
public:
    CCoInitialize() : m_hr(CoInitialize(NULL)) { }
    ~CCoInitialize() { if (SUCCEEDED(m_hr)) CoUninitialize(); }
    operator HRESULT() const { return m_hr; }
private:
    HRESULT m_hr;
};


bool test()
{
    CCoInitialize co;
    CComPtr<IKnownFolderManager> knownFolderManager;
    HRESULT hr = knownFolderManager.CoCreateInstance( CLSID_KnownFolderManager );
    if( !SUCCEEDED(hr) ) {
        _com_error err(hr);
        std::wcout << L"Error while creating KnownFolderManager: " << err.ErrorMessage() << std::endl;
        return false;
    }

    CComPtr<IKnownFolder> folder;
    hr = knownFolderManager->FindFolderFromPath( L"C:\\Users\\All Users\\Microsoft", FFFP_NEARESTPARENTMATCH, &folder );
    if( SUCCEEDED(hr) ) {
        PrintKnownFolder(folder);
    } else {
        _com_error err(hr);
        std::wcout << L"Error while querying KnownFolderManager for nearest match: " << err.ErrorMessage() << std::endl;
    }

    // dispose it.
    folder.Attach( NULL );

    hr = knownFolderManager->FindFolderFromPath( L"C:\\Users\\All Users\\Microsoft", FFFP_EXACTMATCH, &folder );
    if( SUCCEEDED(hr) ) {
        PrintKnownFolder(folder);
    } else {
        _com_error err(hr);
        std::wcout << L"Error while querying KnownFolderManager for exact match: " << err.ErrorMessage() << std::endl;
    }

    return true;
}

CCoInitialize borrowed from The Old New Thing