unique_hkey RegistryQuery::OpenKeyFromString()

in library/src/RegistryQuery.cpp [74:110]


unique_hkey RegistryQuery::OpenKeyFromString(wstring_view key)
{
	// Our list of supported root keys
	static map<wstring, HKEY> rootKeys = {
		{ L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT },
		{ L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG },
		{ L"HKEY_CURRENT_USER", HKEY_CURRENT_USER },
		{ L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE },
		{ L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA },
		{ L"HKEY_USERS", HKEY_USERS }
	};
	
	// Verify that the supplied key path is well-formed
	size_t backslash = key.find_first_of(L"\\");
	if (backslash == wstring_view::npos || backslash >= (key.size()-1)) {
		throw CreateError(L"invalid registry key path: " + wstring(key));
	}
	
	// Split the root key name from the rest of the path
	wstring rootKeyName = wstring(key.substr(0, backslash));
	wstring keyPath = wstring(key.substr(backslash + 1));
	
	// Identify the handle for the specified root key
	auto rootKey = rootKeys.find(rootKeyName);
	if (rootKey == rootKeys.end()) {
		throw CreateError(L"unknown registry root key: " + rootKeyName);
	}
	
	// Attempt to open the key
	unique_hkey keyHandle;
	auto error = CheckWin32(RegOpenKeyExW(rootKey->second, keyPath.c_str(), 0, KEY_READ, keyHandle.put()));
	if (error) {
		throw error.Wrap(L"failed to open registry key " + wstring(key));
	}
	
	return keyHandle;
}